問題描述
MongoDB:跨文檔列表中的項目不同 (MongoDB: distinct of items inside a list across documents)
我的項目位於以下集合中:
{
"_id": {
"$oid": "6092037099edca65f29c09d0"
},
"items": [{"name": "item1"}, {"name": "item2"}, {"name": "item3"}]
}
我想運行一個查詢,返回所有集合中的不同項目。
參考解法
方法 1:
You can use Aggregation Framework and Group Operation to get distinct items.
First, get documents with only one item instead of array of items. Then, group these documents by item. You will get as many groups as unique items in the arrays exist. And, finally, project _id_
field of the groups to the one you need.
Here is an example of Mongo query:
db.collection.aggregate([
{
$unwind: '$items'
},
{
$group: {
_id: "$items"
}
},
{
$project: {
"_id": 0,
"item": "$_id"
}
}
])
(by thecheech、Igor Amelin)