[英]Combine 2 collections into a single collection mongoDB
I have 2 collections in mongoDB 我在mongoDB中有2个集合
collection 1 收集1
{
_id : "123",
name : "ABC1"
}
collection 2 收集2
{
_id : "456",
name : "DEF1"
}
I'm trying to combine write a query that gives me an output like so 我正在尝试结合写一个查询,给我一个像这样的输出
Output 产量
[
{
_id : "123",
name : "ABC1"
},
{
_id : "456",
name : "DEF1"
}
]
I've tried lookup but that seems to append 1 collection to the other, I want the collections to be merged like shown in the output. 我尝试过查找,但似乎将1个集合附加到另一个集合,我希望合并集合,如输出中所示。 I have looked at the existing solutions on stack overflow and they all suggest using lookup
which does not give me the output that I require. 我已经查看了堆栈溢出的现有解决方案,他们都建议使用lookup
,这不会给我我需要的输出。
进行两个独立的查询并将它们组合在
const output = [query1, query2];
This can be done through javascript
code on mongo shell as follow: 这可以通过mongo shell上的javascript
代码完成,如下所示:
> var all = []; // initialize a variable with empty values
> db.collection1.find().forEach(function (obj) {all.push(obj);}) // push to all from collection 1
> db.collection2.find().forEach(function (obj) {all.push(obj);}) // push to all from collection 2
> printjson(all) // Print all pushed elements
[
{
"_id" : "123",
"name" : "ABC1"
},
{
"_id" : "456",
"name" : "DEF1"
}
]
Hope this will help you. 希望这会帮助你。 You can perform this on mongo shell. 你可以在mongo shell上执行此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.