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

旧时模样 提交于 2019-12-05 21:37:15

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