如何使用$ addToSet成为一个带对象的数组?

问题描述 投票:1回答:1

我有一个包含大量文档的集合。

我的文档结构如下:

这是一个api可以获取json数据:

https://obscure-reaches-65656.herokuapp.com/api?city=TaipeiEast&theater=Centuryasia

enter image description here

我想查询我的数据没有重复enName,所以我尝试使用$addToSet

这是我的查询命令:

db.getCollection('Keelung').aggregate([
  { "$match": {
        "theater": "Centuryasia"
      }
  },
  { "$unwind": '$movie' },
  { "$group": {
      "_id": "$_id",
      "enName": {
        "$addToSet": "$movie.enName" 
       },
       "photoHref": {
         "$addToSet": "$movie.photoHref" 
       }
    } 
  }
])

查询结果将是这样的:enter image description here

我希望结构可以像:

movie: [
  { enName: "value", photoHref: "value"},
  { enName: "value", photoHref: "value"},
  ...
]

我尝试添加$push

db.getCollection('Keelung').aggregate([
      { "$match": {
            "theater": "Centuryasia"
          }
      },
      { "$unwind": '$movie' },
      { "$group": {
          "_id": "$_id",
          "enName": {
            "$addToSet": "$movie.enName" 
           },
           "photoHref": {
             "$addToSet": "$movie.photoHref" 
           }
        },
        "movie": {
          "$push": {
            "enName": "$enName",
            "photoHref": "$photoHref",
          }
        } 
      }
    ])

它不起作用。

任何帮助,将不胜感激。提前致谢。

mongodb
1个回答
1
投票

您可以尝试以下聚合

db.collection.aggregate([
  { "$match": { "theater": "Centuryasia" }},
  { "$unwind": "$movie" },
  { "$group": {
      "_id": "$_id",
      "theater": { "$first": "$theater" },
      "phone": { "$first": "$phone" },
      "geometry": { "$first": "$geometry" },
      "theaterPhoto": { "$first": "$theaterPhoto" },
      "address": { "$first": "$address" },
      "theaterCn": { "$first": "$theaterCn" },
      "movie": {
        "$addToSet": {
          "enName": "$movie.enName",
          "photoHref": "$movie.photoHref"
        }
      }
    }
  }
])
© www.soinside.com 2019 - 2024. All rights reserved.