在MongoDB-3.2.7中的一个查询中从两个集合中获取所需的文档

时间:2016-07-19 10:13:48

标签: mongodb mongodb-query mongodb-java

我在MongoDB中有两个如下所示的集合。

lookupcol1

{ "_id" : 1, "sku" : "abc", description: "product 1", "instock" : 120, "groupId":100100},
{ "_id" : 2, "sku" : "def", description: "product 2", "instock" : 80,"groupId":100100 },
{ "_id" : 3, "sku" : "ijk", description: "product 3", "instock" : 60 },
{ "_id" : 4, "sku" : "jkl",description: "product 4", "instock" : 70 },
{ "_id" : 5, "sku": null, description: "Incomplete", "groupId":100100 },
{ "_id" : 6 }

lookupcol2

{ "_id" : 12, "sku" : "bcd", description: "product 2", "instock" : 121, "groupId":100100},
{ "_id" : 23, "sku" : "def", description: "product 2", "instock" : 810, "groupId":100100},
{ "_id" : 34, "sku" : "ijk", description: "product 3", "instock" : 60,"groupId":100100 },
{ "_id" : 45, "sku" : "jkl",description: "product 4", "instock" : 70 },
{ "_id" : 56, "sku": "def", description: "Incomplete","groupId":100100 },
{ "_id" : 67, "groupId":100100}

我想从两个集合中获取文件,其中包含" groupId"为100100。

预期结果应如下所示。

结果:

{ "_id" : 1, "sku" : "abc", description: "product 1", "instock" : 120, "groupId":100100},
{ "_id" : 2, "sku" : "def", description: "product 2", "instock" : 80,"groupId":100100 },
{ "_id" : 5, "sku": null, description: "Incomplete", "groupId":100100 },
{ "_id" : 12, "sku" : "bcd", description: "product 2", "instock" : 121, "groupId":100100},
{ "_id" : 23, "sku" : "def", description: "product 2", "instock" : 810, "groupId":100100},
{ "_id" : 34, "sku" : "ijk", description: "product 3", "instock" : 60,"groupId":100100 },
{ "_id" : 56, "sku": "def", description: "Incomplete","groupId":100100 },
{ "_id" : 67, "groupId":100100}

任何人都可以告诉我如何获得以上输出。

1 个答案:

答案 0 :(得分:0)

var q = {groupId: 100100};
var r1 = db.lookupcol1.find(q);
var r2 = db.lookupcol2.find(q);
r1.concat(r2);