MongoDB Compass 过滤器动态数组

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

我有一个结构如下的集合,其中每个记录的 ids(abc,cde) 不一致,并且 0,1 对象可以更改。在某些情况下它可以是0,在其他情况下可以是1、2、3、4。我想过滤国家=美国,但不知道该怎么做。

ids:Object
 abc: Array
   0: Object
     name: "Ted"
     country: "US"
   1: Object
     name: "Matt"
     country: "DE"
 cde: Array
   0: Object
     name: "Lisa"
     country: "US"
   1: Object
     name: "Tina"
     country: "CA"

json:

"id":{
 "abc": [
   {"name":"Ted",
    "country":"US"
    },
   {"name":"Matt",
    "country":"DE"
    }
   ],
  "cde": [
   {"name":"Lisa",
    "country":"US"
    },
   {"name":"Tina",
    "country":"CA"
    }
   ]
  }
arrays mongodb filtering compass
1个回答
0
投票

我认为您正在寻找这个:

db.collection.aggregate([
   { $set: { ids: { $objectToArray: "$ids" } } },
   {
      $set: {
         ids: {
            $map: {
               input: "$ids",
               as: "item",
               in: {
                  k: "$$item.k",
                  v: {
                     $filter: {
                        input: "$$item.v",
                        cond: { $eq: ["$$this.country", 'US'] }
                     }
                  }
               }
            }
         }
      }
   },
   { $set: {ids: {$arrayToObject: "$ids"}} }
])

蒙戈游乐场

© www.soinside.com 2019 - 2024. All rights reserved.