How can I work with “join” to export data from MongoDB?

房东的猫 提交于 2019-12-07 18:14:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!