如何在MongoDB中的多个子文档中重新组合具有相同字段的内容?

huangapple go评论66阅读模式
英文:

How to regoup in subdocuments, multi document that have a same field in MongoDB?

问题

我有一个在mongoDB中的集合,看起来像这样:

db.mycollection.find({}) 

{
    "_id" : ObjectId("5deb4ce4bbe1b67e6e5611e4"),
    "site" : "MDC",
    "label" : "407",
    "status" : "removed"
}

{
    "_id" : ObjectId("5def36379ca17632de773d7e"),
    "site" : "MDC",
    "label" : "407",
    "status" : "new"
}

{
    "_id" : ObjectId("5df4740eab0d76657c19a7d2"),
    "site" : "MDC",
    "label" : "408",
    "status" : "new"
}

我想要将具有相同字段"label"值的文档重新分组到一个文档中,并具有"status"的子文档,以获得如下所示的结果:

{
    "_id" : ObjectId("5deb4ce4bbe1b67e6e5611e4"),
    "site" : "MDC",
    "label" : "407",
    "status" : [ 
    {
        "label" : "new"
    }, 
    {
        "label" : "removed"
    }
    ]
}

我尝试了不同的方法(聚合、更新等)来做到这一点,但都失败了...

英文:

I have a collection in mongoDB that looks like this :

db.mycollection.find({}) 

{
    "_id" : ObjectId("5deb4ce4bbe1b67e6e5611e4"),
    "site" : "MDC",
    "label" : "407",
    "status" : "removed"
}

{
    "_id" : ObjectId("5def36379ca17632de773d7e"),
    "site" : "MDC",
    "label" : "407",
    "status" : "new"
}

{
    "_id" : ObjectId("5df4740eab0d76657c19a7d2"),
    "site" : "MDC",
    "label" : "408",
    "status" : "new"
}

I would like to regroup my documents that have the same value for the field "label" in one document with subdocument of the status, to have something like this :

{
    "_id" : ObjectId("5deb4ce4bbe1b67e6e5611e4"),
    "site" : "MDC",
    "label" : "407",
    "status" : [ 
    {
        "label" : "new"
    }, 
    {
        "label" : "removed"
    }
]
}

I tried different ways (aggregate, update,..) to do this but it's a complete fail...

答案1

得分: 1

你需要按照labelsite进行$group操作,以便将状态信息进行$push

db.collection.aggregate([
    {
        $group: {
            _id: "$label",
            old_id: { $first: "$_id" },
            site: { $first: "$site" },
            status: { $push: { label: "$status" } }
        }
    },
    {
        $project: {
            _id: "$old_id",
            site: 1,
            label: "$_id",
            status: 1
        }
    }
])

Mongo Playground

英文:

You need to $group by label or site in order to $push your statuses:

db.collection.aggregate([
    {
        $group: {
            _id: "$label",
            old_id: { $first: "$_id" },
            site: { $first: "$site" },
            status: { $push: { label: "$status" } }
        }
    },
    {
        $project: {
            _id: "$old_id",
            site: 1,
            label: "$_id",
            status: 1
        }
    }
])

Mongo Playground

huangapple
  • 本文由 发表于 2020年1月6日 23:14:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/59614550.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定