gpt4 book ai didi

mongodb - 如何使用 "join"从 MongoDB 导出数据?

转载 作者:可可西里 更新时间:2023-11-01 09:35:47 24 4
gpt4 key购买 nike

我有 2 个集合:

列表 1 和列表 2。

list1有一些字段,list2有其他字段,包括引用list1的id。

我需要做一个查询来导出 list1 上的所有项目,这些项目在 list2 上至少有一个项目引用了他。

我该怎么做?这有点像从 list1 到 list2 的连接。

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

最佳答案

我这样做的方法是创建一个简短的 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>

关于mongodb - 如何使用 "join"从 MongoDB 导出数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31974925/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com