问题
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