使用另一个查询的结果在 MongoDB 中查找文档
Find documents in MongoDB using result of another query
我是 MongoDB 的新手,我正在尝试在集合 A
中查找文档,其中字段 _id
等于集合 [中的字段 excel_template
=15=].
var r = db.B.find({"name":/.*aco.*/}, {excel_template:1, _id:0}).excel_template;
db.A.find({"_id":{$eq: "${r}" }})
但我很难做到。它没有给我任何结果,但它应该给我一个结果。任何建议将不胜感激
find
returns a cursor
到匹配的文档。所以查询
db.B.find({ "name": /.*aco.*/ }, { "excel_template": 1, "_id": 0 })
不会 return 单个文档,而是 cursor
匹配上述查询条件的文档。
您可以使用 distinct()
方法 return 来自与上述查询匹配的文档的 excel_template
值数组,并使用在另一个查询中,如:
var r = db.B.distinct("excel_template", { "name": /.*aco.*/ });
db.A.find({ "_id": { "$in": r } });
或
MongoDB 3.2 及更新版本:
您还可以使用聚合框架,其中 $lookup
管道将提供连接两个集合和 运行 单个查询的功能操作
db.B.aggregate([
{ "$match": { "name": /.*aco.*/ } },
{
"$lookup": {
"from": "A",
"localField": "excel_template",
"foreignField": "_id",
"as": "bList"
}
}
])
我是 MongoDB 的新手,我正在尝试在集合 A
中查找文档,其中字段 _id
等于集合 [中的字段 excel_template
=15=].
var r = db.B.find({"name":/.*aco.*/}, {excel_template:1, _id:0}).excel_template;
db.A.find({"_id":{$eq: "${r}" }})
但我很难做到。它没有给我任何结果,但它应该给我一个结果。任何建议将不胜感激
find
returns a cursor
到匹配的文档。所以查询
db.B.find({ "name": /.*aco.*/ }, { "excel_template": 1, "_id": 0 })
不会 return 单个文档,而是 cursor
匹配上述查询条件的文档。
您可以使用 distinct()
方法 return 来自与上述查询匹配的文档的 excel_template
值数组,并使用在另一个查询中,如:
var r = db.B.distinct("excel_template", { "name": /.*aco.*/ });
db.A.find({ "_id": { "$in": r } });
或
MongoDB 3.2 及更新版本:
您还可以使用聚合框架,其中 $lookup
管道将提供连接两个集合和 运行 单个查询的功能操作
db.B.aggregate([
{ "$match": { "name": /.*aco.*/ } },
{
"$lookup": {
"from": "A",
"localField": "excel_template",
"foreignField": "_id",
"as": "bList"
}
}
])