【问题标题】:Find documents in MongoDB using result of another query使用另一个查询的结果在 MongoDB 中查找文档
【发布时间】:2017-06-24 15:02:44
【问题描述】:

我是 MongoDB 新手,我正在尝试在集合 A 中查找文档,其中字段 _id 等于集合 B 中的字段 excel_template

var r = db.B.find({"name":/.*aco.*/}, {excel_template:1, _id:0}).excel_template;
db.A.find({"_id":{$eq: "${r}" }})

但我很难做到。它没有给我任何结果,而它应该给我一个结果。任何建议将不胜感激

【问题讨论】:

  • db.A.find({"_id":{$in: r}}) ?..
  • Can't canonicalize query: BadValue $in needs an array
  • 如果你 var r = db.B.find({"name":/.*aco.*/}, {excel_template:1, _id:0}); db.A.find({"_id":{$in: r.excel_template}}) ?..
  • error: { "$err" : "Can't canonicalize query: BadValue $in needs an array", "code" : 17287 }
  • 你运行什么 mongo 版本?

标签: mongodb mongodb-query robo3t


【解决方案1】:

findcursor 返回到匹配的文档。所以查询

db.B.find({ "name": /.*aco.*/ }, { "excel_template": 1, "_id": 0 })

不会向与上述查询条件匹配的文档返回单个文档,而是返回 cursor

您可以使用 distinct() 方法从与上述查询匹配的文档中返回一组 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"
        }
    }
])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-06
    • 2016-05-08
    • 1970-01-01
    相关资源
    最近更新 更多