MongoDB$在对象/文档数组上查找 [英] Mongodb $lookup on array of objects/documents

查看:35
本文介绍了MongoDB$在对象/文档数组上查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的orders集合的文档架构如下:

{
"_id" : ObjectId("Id of this record"),
    "location_data" : {
        "type" : "main",
        "location_id" : ObjectId("this location's id")
    },
    "item_details" : [
        {
            "item_id" : ObjectId("this item's id"),
            "qty" : 950
        },
        {
            "item_id" : ObjectId("this item's id"),
            "qty" : 200
        }
    ]
}

我将items存储在另一个集合中,该集合的架构如下所示:

{
    "_id": ObjectId("this record's id"),
    "title": "this item's title",
    "description": "this item's description"
}

我想要的输出是:

{
"_id" : ObjectId("Id of this record"),
    "location_data" : {
        "type" : "main",
        "location_id" : ObjectId("this location's id")
    },
    "item_details" : [
        {
            "title": "this item's title",
            "item_id" : ObjectId("this item's id"),
            "qty" : 950
        },
        {
            "title": "this item's title",
            "item_id" : ObjectId("this item's id"),
            "qty" : 200
        }
    ]
}

在MongoDB文档中,我没有找到任何可以使用对象数组的内容。任何帮助都是值得感激的。

谢谢

推荐答案

尝试以下聚合查询:

db.orders.aggregate([
    {$unwind : "$item_details"},  // Since the item_details is an array, unwind it first
    {$lookup:     // run the $lookup to join with `items` collections
        {
            from: "items", 
            localField: "item_details.item_id",
            foreignField: "_id",
            as: "item_detailsTemp"
        }
    },
    { 
        $addFields: { "item_details" : { $mergeObjects: [ { $arrayElemAt: [ "$item_detailsTemp", 0 ] }, "$item_details" ] } } // Replace the existing item_details with new information 
    },
    {
        $group : { // Since you've ran the $unwind at early stage, group it to make the item_details as an array again
           "_id" : "$_id", 
           "location_data" : {$first : "$location_data"}, 
           "item_details" : {$push : "$item_details"}}
    }
])
// Voila! Hope this helps! 

这篇关于MongoDB$在对象/文档数组上查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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