聚合嵌套对象mongodb

时间:2018-11-18 12:45:04

标签: mongodb multidimensional-array aggregation-framework aggregate

请帮助我使用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”]的特定用户。

2 个答案:

答案 0 :(得分:2)

您可以使用以下汇总

在管道的开头使用$match过滤掉"a"数组中不包含"b"tags的文档。然后将$filter$setIsSubset一起使用,以过滤出嵌套数组。

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

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

答案 1 :(得分:0)

您需要将$ unwind和$ filter一起使用:

db.collection.aggregate([
      {
        $unwind: "$users"
      },
      {
        $match: {
          "users.tags": "a"
        }

      }
    ])

结果:

[
  {
    "_id": ObjectId("5a934e000102030405000000"),
    "id": 1,
    "shouldPay": true,
    "users": {
      "id": 100,
      "tags": [
        "a",
        "b",
        "c",
        "d"
      ]
    }
  }
]