首页 > 解决方案 > 聚合嵌套对象 mongodb

问题描述

你能帮我用mongodb写一些聚合查询吗?

我有下一个数据结构。

[
    {
        id: 1,
        shouldPay: true,
        users: [
            {
                id: 100,
                items: [{...}],
                tags: ['a', 'b', 'c', 'd']
            },
            {
                id: 100,
                items: [{...}],
                tags: ['b', 'c', 'd']
            },
            {
                id: 100,
                items: [{...}],
                tags: ['c', 'd']
            }
        ],

    }
]

结果我想得到类似的东西:

[
    {
        id: 1,
        shouldPay: true,
        user: {
            id: 100,
            items: [{...}],
            tags: ['a', 'b', 'c', 'd']
        }

    }
]

主要思想是选择在标签中具有“a”字母或字母列表['a','b']的特定用户。

标签: mongodbmultidimensional-arrayaggregation-frameworkaggregate

解决方案


您可以使用以下聚合

在管道的开头使用$match过滤掉不包含"a""b"tags数组中的文档。然后使用$filterwith$setIsSubset过滤掉嵌套数组。

$arrayELemAt从数组中返回指定的元素。

db.collection.aggregate([
  { "$match": { "users.tags": { "$in": ["a", "b"] }}},
  { "$project": {
    "users": {
      "$arrayElemAt": [
        { "$filter": {
          "input": "$users",
          "cond": { "$setIsSubset": [["a", "b"], "$$this.tags"] }
        }},
        0
      ]
    }
  }}
])

推荐阅读