Tôi có một số items
bộ sưu tập như thế này:MongoDB - tổng hợp và nối kết quả vào nhóm
[
{ name: 'item1', description: 'description #1', categories: 'cat_A; cat_B'},
{ name: 'item2', description: 'description #2', categories: 'cat_B'},
{ name: 'item3', description: 'description #3', categories: 'cat_C; cat_B'},
{ name: 'item4', description: 'description #4', categories: 'cat_B; cat_A'},
{ name: 'item5', description: 'description #5', categories: 'cat_B'},
{ name: 'item6', description: 'description #6', categories: 'cat_D'}
]
Tôi muốn tìm và lọc kết quả theo loại. Tôi tạo ra truy vấn Mongo:
db.getCollection('items')
.aggregate([
{
$match: {
categories: {$in: [/cat_a/i, /cat_b/i]}
}
}, {
$group: {
_id: "$categories",
items: { $push: { name: "$name", description: '$description' } }
}
}
])
Vì vậy, nó sẽ trả về cho tôi này:
result : [
{
"_id" : "cat_B; cat_C",
"items" : [
{
"name" : "item3",
"description" : "description #3"
}
]
}, {
"_id" : "cat_B; cat_A",
"items" : [
{
"name" : "item4",
"description" : "description #4"
}
]
}, {
"_id" : "cat_B",
"items" : [
{
"name" : "item2",
"description" : "description #2"
},
{
"name" : "item5",
"description" : "description #5"
}
]
}, {
"_id" : "cat_A; cat_B",
"items" : [
{
"name" : "item1",
"description" : "description #1"
}
]
}
]
Những gì tôi muốn đạt được là:
result : [
{
"_id" : "cat_A",
"items" : [
{
"name" : "item1",
"description" : "description #1"
},
{
"name" : "item4",
"description" : "description #4"
}
]
}, {
"_id" : "cat_B",
"items" : [
{
"name" : "item1",
"description" : "description #1"
},
{
"name" : "item2",
"description" : "description #2"
},
{
"name" : "item3",
"description" : "description #3"
},
{
"name" : "item4",
"description" : "description #4"
},
{
"name" : "item5",
"description" : "description #5"
}
]
}
]
Là có thể trong truy vấn Mongo tinh khiết?
chúng ta có thể sử dụng 'chia ("")' và 'trim' cho một dọn dẹp nhỏ. – profesor79
Thật không may, tôi không thể sửa đổi bất kỳ trường nào trong bộ sưu tập này và tôi cần giữ 'danh mục' làm chuỗi. – zucker
Sau đó, tạo một trường bổ sung lưu trữ bộ danh mục riêng biệt và bạn có thể giữ trường danh mục ban đầu như cũ. Khi bạn chạy đường ống tổng hợp, bạn có thể '$ relax' và nhóm theo trường mới. – chridam