在MongoDB-3.2.7中的一个查询中从两个集合中获取所需的文档 [英] Getting the required documents from both the collections in one query in MongoDB-3.2.7

查看:135
本文介绍了在MongoDB-3.2.7中的一个查询中从两个集合中获取所需的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在MongoDB中有两个像下面这样的集合.

I have two collections like below in MongoDB.

{ "_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的集合中获取文档.

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

预期结果应显示如下.

The expected result should be shown below.

结果:

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

推荐答案

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

这篇关于在MongoDB-3.2.7中的一个查询中从两个集合中获取所需的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆