【问题标题】:Mongodb: Not expected result from aggregate ($lookup)Mongodb:聚合的结果不是预期的($lookup)
【发布时间】:2018-05-16 04:13:24
【问题描述】:

我正在寻求帮助。

我有一个名为“business”的集合,其中有这样的对象:

[{
    "_id": ObjectId("5aefa97166763d28fc984c7a"),
    "name": "Business 1",
    "boxes": [
        {
            "_id": ObjectId("5ac6bb69f3c36e17f0d34bd2")
        }
    ]
}]

还有一个名为 box 的集合,它的对象如下:

[{
    _id: ObjectId("5ac6bb69f3c36e17f0d34bd2"),
    name:"Box1",
    color:"blue"
}]

这里的想法是有些企业拥有盒子,我希望将这两个收藏分开。

也就是说,我想检索这个结果:

[{
    "_id": ObjectId("5aefa97166763d28fc984c7a"),
    "name": "Business 1",
    "boxes": [{
        _id: ObjectId("5ac6bb69f3c36e17f0d34bd2"),
        name:"Box1",
        color:"blue"
    }]
}]

但我得到了这个结果:

[{
    "_id": ObjectId("5aefa97166763d28fc984c7a"),
    "name": "Business 1",
    "boxes": [
        {
            "_id": ObjectId("5ac6bb69f3c36e17f0d34bd2")
        }
    ]
}]

使用 $lookup 如下所示:

db.db('database').collection("business").aggregate({
    $lookup:{
        from: "boxes",
        localField: "_id",
        foreignField: "_id",
        as: "box"
    },
    "$unwind": "$boxes" 
    }).toArray(function(err, result) {
        if (err) throw err; 
        res.send(result);
        db.close();
        res.end();
    });

我做错了什么?

谢谢大家!

【问题讨论】:

  • localField: 'boxes._id' 你指向了错误的路径。此外,您不需要 $unwind 来获得所需的结果,只需使用 as: 'boxes' 用您的外部集合匹配覆盖 ObjectId 值数组。无论如何,$unwind 是管道中的一个单独文档,但只需删除该行,因为它当前的语法不正确且不需要。

标签: mongodb aggregate lookup ref


【解决方案1】:

这应该会有所帮助

db.business.aggregate([{$lookup:{from: "boxes", localField: "boxes._id", foreignField: "_id", as: "box" }},{"$project":{"_id":1,"name":1,"boxes":"$box"}}])

查找创建一个数组“box”,其中包含来自 box 集合的所有匹配文档。管道中的下一个阶段 $project 从新文档中选择 _id 和 name 并将 box 数组重命名为 box。

【讨论】:

    【解决方案2】:

    如果你有多个 objectIds 并且需要在一个数组中的 Boxes:

    Ex: "boxes": [
            {
                "_id": ObjectId("5ac6bb69f3c36e17f0d34bd2")
            },
           {
                "_id": ObjectId("5ac6bb69f3c36e17f0d34bd3")
            }
        ]
    

    那你需要做group

    查询:

    db.getCollection('business').aggregate([
        {"$unwind": "$boxes"} ,
        {$lookup:{
            from: "boxes",
            localField: "boxes._id",
            foreignField: "_id",
            as: "box"
        }},
        {
          $group: {
            _id: '$_id',
            name: { $first: '$name' },
            boxes: { 
               $push: {
                      _id: '$boxes._id',
                      name: '$boxes.name'
                       color: '$boxes.color'
                     } 
                  }
           }
        }
    
    ])
    

    【讨论】:

      猜你喜欢
      • 2020-01-25
      • 2022-01-05
      • 1970-01-01
      • 1970-01-01
      • 2020-08-19
      • 1970-01-01
      • 2019-03-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多