Studio 3T select 数组列中的所有数组值

Studio 3T select all array values in an array column

我有一个具有当前架构的 Mongo 集合:(简化)

{ 
    "_id" : ObjectId("55a94615a243a426db43d81e"), 
    "property_name" : "My Main Property", 
    "domain_list" : [
        "mynumber1url.com",
        "mynumber2url.com",
        "mynumber3url.com"
    ]
}

我想查询此集合和 return domain_list 的所有元素以及与之关联的 property_name,例如:

mynumber1url.com  My Main Property
mynumber2url.com  My Main Property
mynumber3url.com  My Main Property
mynumber4url.com  My Other Property
...

聚合查询是可以接受的,但我宁愿只用一个 query/projection

一个$unwind阶段就足够了:

db.collection.aggregate([
    {$unwind: '$domain_list'}
])

它将导致:

[{ 
    "_id": ObjectId("55a94615a243a426db43d81e"), 
    "property_name" : "My Main Property", 
    "domain_list" : "mynumber1url.com"
}, { 
    "_id": ObjectId("55a94615a243a426db43d81e"), 
    "property_name" : "My Main Property", 
    "domain_list" : "mynumber2url.com"
}, { 
    "_id": ObjectId("55a94615a243a426db43d81e"), 
    "property_name" : "My Main Property", 
    "domain_list" : "mynumber3url.com"
}]

或者如果你想把它放在一个字符串中(我不确定格式):

db.getCollection('x').aggregate([
    {$unwind: '$domain_list'},
    {$project: {_id: {$concat: ['$property_name', ' ', '$domain_list']}}}
])

这将导致:

[
  {"_id": "My Main Property mynumber1url.com"},
  {"_id": "My Main Property mynumber2url.com"},
  {"_id": "My Main Property mynumber3url.com"}
]

您可以在 3.4.4 及之后的版本中使用以下聚合。

db.colname.aggregate([
  {"$replaceRoot":{"newRoot":
   {"$arrayToObject":{
      "$map":{
        "input":"$domain_list",
        "as":"dl",
        "in":{
         "k":"$$dl",
         "v":"$property_name"
        }
      }
    }}
  }}
])

输出:

{ 
  "mynumber1url.com" : "My Main Property", 
  "mynumber2url.com" : "My Main Property", 
  "mynumber3url.com" : "My Main Property" 
}