【问题标题】:Extract child objects into array inside MongoDB aggregation将子对象提取到 MongoDB 聚合中的数组中
【发布时间】:2018-11-29 23:42:16
【问题描述】:

在我的集合中,我所有的文档都有一个名为 tags 的数组:

"tags" : [
        {
            "name" : "a", 
            "weight" : NumberInt(32)
        }, 
        {
            "name" : "b", 
            "weight" : NumberInt(26)
        }, 
        {
            "name" : "c", 
            "weight" : NumberInt(25)
        }, 
        ...
]

数组中的每个对象都有键 nameweight。我需要删除weight 键,这样我就只剩下names 在像["a", "b", "c"...] 这样的单级数组中了


解释为什么我需要这样做:

在我的聚合中,我想计算数组 x = ["a", "b", "d"] 与每个文档具有的任何标签之间的匹配数。

据我所知,在 $project 中我创建了一个新变量,如下所示:

"$project": {
    ...
    "diff": {
       "$size": {
          "$setIntersection": [ x, "$tags" } ]
       }
    },
    ...
}

但这当然行不通,因为$tags 数组中充满了对象,而不是字符串。我需要从标签数组中删除weight,并将其保留为names 的数组,如["a", "b", "c" ...],那么它应该可以工作。

我该怎么做呢?

【问题讨论】:

    标签: mongodb mongodb-query aggregation-framework pymongo


    【解决方案1】:

    只需在tags 中使用name. dot 符号即可。像

    db.collection.aggregate([
      { "$project": {
        "matches": {
          "$size": {
            "$setIntersection": [
              [ "a", "b", "d"],
              "$tags.name"
            ]
          }
        }
      }}
    ])
    

    【讨论】:

    • 谢谢,它运行良好。没想到这么简单
    猜你喜欢
    • 2020-07-02
    • 1970-01-01
    • 1970-01-01
    • 2021-06-21
    • 1970-01-01
    • 2020-05-05
    • 1970-01-01
    • 1970-01-01
    • 2018-04-20
    相关资源
    最近更新 更多