在mongo中将多个子文档合并为一个新文档 [英] Combining multiple sub-documents into a new doc in mongo

查看:93
本文介绍了在mongo中将多个子文档合并为一个新文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在MongoDB中查询多个子文档并作为一个文档返回. 我认为聚合框架是必经之路,但看不到完全正确.

I am trying to query multiple sub-documents in MongoDB and return as a single doc. I think the aggregation framework is the way to go, but, can't see to get it exactly right.

使用以下文档:

{
    "board_id": "1",
    "hosts": 
     [{
        "name": "bob",
        "ip": "10.1.2.3"
     },
    {
         "name": "tom",
         "ip": "10.1.2.4"
    }]
 }

{
    "board_id": "2",
    "hosts": 
    [{
        "name": "mickey",
        "ip": "10.2.2.3"
    },
    {
        "name": "mouse",
        "ip": "10.2.2.4"
    }]
}

{
     "board_id": "3",
     "hosts": 
    [{
        "name": "pavel",
        "ip": "10.3.2.3"
    },
    {
        "name": "kenrick",
        "ip": "10.3.2.4"
     }]
}

试图获得这样的查询结果:

Trying to get a query result like this:

{
    "hosts": 
    [{
        "name": "bob",
        "ip": "10.1.2.3"
    },
    {
         "name": "tom",
         "ip": "10.1.2.4"
    },
    {
         "name": "mickey",
         "ip": "10.2.2.3"
    },
    {
        "name": "mouse",
        "ip": "10.2.2.4"
    }, 
    {
         "name": "pavel",
         "ip": "10.3.2.3"
     },
     {
        "name": "kenrick",
        "ip": "10.3.2.4"
     }]
}

我已经尝试过了:

db.collection.aggregate([ { $unwind: '$hosts' }, { $project : { name: 1, hosts: 1, _id: 0 }} ])

但这不是我想要的.

推荐答案

您绝对可以使用聚合来做到这一点.假设您的数据位于名为board的集合中,那么请使用您的集合名称替换它.

You can definitely do this with aggregate. Let's assume your data is in collection named board, so please replace it with whatever your collection name is.

db.board.aggregate([
{$unwind:"$hosts"},
{$group:{_id:null, hosts:{$addToSet:"$hosts"}}},
{$project:{_id:0, hosts:1}}
]).pretty()

它将返回

    {
        "hosts" : [
            {
                "name" : "kenrick",
                "ip" : "10.3.2.4"
            },
            {
                "name" : "pavel",
                "ip" : "10.3.2.3"
            },
            {
                "name" : "mouse",
                "ip" : "10.2.2.4"
            },
            {
                "name" : "mickey",
                "ip" : "10.2.2.3"
            },
            {
                "name" : "tom",
                "ip" : "10.1.2.4"
            },
            {
                "name" : "bob",
                "ip" : "10.1.2.3"
            }
        ]
    }

这篇关于在mongo中将多个子文档合并为一个新文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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