3

我有 2 个收藏:

清单 1 和清单 2。

list1 有一些字段,list2 有另一个字段,包括引用 list1 的 id。

我需要进行查询以导出 list1 上至少有一个项目在 list2 上引用他的所有项目。

我怎样才能做到这一点?这类似于从 list1 到 list2 的连接。

我需要运行 mongoexport 命令来生成 csv 文件。

4

1 回答 1

3

我这样做的方法是创建一个简短的 javascript 程序,它将您要导出的数据传输到一个新的临时集合中,然后您可以将其导出。

例如,创建一个文件 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");

然后,您可以从 cmd 行运行它:

# mongo "localhost:27017/<dbname>" export.js

这将创建一个名为 export.results 的集合,其中包含来自 list1 集合的文档以及 list2 集合中具有匹配 id 字段的文档。然后,您可以导出或转储此集合:

# mongoexport --db <dbname> -c export.results -type csv -o <file_name>
于 2015-08-12T22:01:32.003 回答