问题
I have 2 collections:
list1 and list2.
list1 have some fields and list2 have another fields, including the id referring to list1.
I need to do a query to export all items on list1 that have at least one item referring to him on list2.
How can I do this? It's something like a join from list1 to list2.
I need to run a mongoexport command to generate a csv file.
回答1:
The way I do this is to create a short javascript program that will transfer the data you want to export into a new temporary collection, which you can then export.
For example, create a file export.js:
//initialise the export results collection
db.export.results.drop();
//create a cursor containing the contents of the list1 collection
cursor = db.list1.find();
while (cursor.hasNext()) {
doc = cursor.next();
//Check if the document exists in the list2 collection
list2 = db.list2.find({"<id_fieldname>": doc.<id_fieldname>});
if (list2.hasNext()) {
//if it does exist, add the document from list1 to the new export collection
db.export.results.insert(doc);
}
}
print(db.export.results.count() + " matching documents found");
you can then run this from the cmd line:
# mongo "localhost:27017/<dbname>" export.js
this will create a collection called export.results containing the document from the list1 collection with documents in the list2 collection with a matching id field. You can then export or dump this collection:
# mongoexport --db <dbname> -c export.results -type csv -o <file_name>
来源:https://stackoverflow.com/questions/31974925/how-can-i-work-with-join-to-export-data-from-mongodb