在您使用aggregation framework 与$unwind 和$group 的文档中:
db.collection.aggregate([
// Match documents with the required criteria
{ "$match": { "charges.amount": 500 } },
// Unwind to de-normalize the content
{ "$unwind": "$charges" },
// Filter the de-normalized documents
{ "$match": { "charges.amount": 500 } },
// Group back the result
{ "$group": {
"_id": null,
"charges": { "$push": "$charges" }
}}
])
或者在现代版本中更有效的是先过滤数组:
db.collection.aggregate([
// Match documents with the required criteria
{ "$match": { "charges.amount": 500 } },
// Pre filter the array
{ "$redact": {
"$cond": {
"if": { "$eq": [{ "$ifNull": [ "$amount", 500 ] }, 500 ]},
"then": "$$DESCEND",
"else": "$$PRUNE"
}
}},
// Unwind to de-normalize the content
{ "$unwind": "$charges" },
// Group back the result
{ "$group": {
"_id": null,
"charges": { "$push": "$charges" }
}}
])
未来版本(在当前开发版本中工作)将有一个更有用的$filter 方法:
db.collection.aggregate([
// Match documents with the required criteria
{ "$match": { "charges.amount": 500 } },
// Filter the array
{ "$project": {
"charges": {
"$filter": {
"input": "$charges",
"as": "charge",
"cond": {
"$eq": [ "$$charge.amount", 500 ]
}
}
}
}},
// Unwind to de-normalize the content
{ "$unwind": "$charges" },
// Group back the result
{ "$group": {
"_id": null,
"charges": { "$push": "$charges" }
}}
])
所有结果:
{
"_id": null,
"charges": [
{
amount: 500,
description: 'foo'
}, {
amount: 500,
description: 'foo'
}
]
}