Getting the required documents from both the collections in one query in MongoDB-3.2.7

瘦欲@ 提交于 2020-01-03 04:25:52

问题


I have two collections like below in 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}

I want to fetch the documents from both the collections which has "groupId" as 100100.

The expected result should be shown below.

Result:

{ "_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}

Could any body please tell me how to get above output.


回答1:


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


来源:https://stackoverflow.com/questions/38455609/getting-the-required-documents-from-both-the-collections-in-one-query-in-mongodb

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