1

我有一个当前模式的 Mongo 集合:(简化)

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

我想查询这个集合并返回 domain_list 的所有元素以及与之关联的 property_name,例如:

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

聚合查询是可以接受的,但我宁愿只用一个查询/投影就可以做到

4

2 回答 2

1

一个$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"}
]
于 2018-07-16T20:56:36.947 回答
1

您可以在 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" 
}
于 2018-07-16T21:02:33.457 回答