最好使用搜索$where https://docs.mongodb.com/manual/reference/operator/query/where/除了正常的查询之外,仍然将内容保留在服务器上:
db.getCollection('collection').find({
"array": {
"$elemMatch": { "field": "BCD", "enabled": "true" },
},
"$where": function() {
return this.array.map((e,i) => Object.assign(e,{ i }))
.filter( e => e.field === "BCD" && e.enabled === "true" )
.map( e => e.i )[0] <=
this.array.map(e => e.enabled).indexOf("true")
}
})
如果您有 MongoDB 3.4 支持$indexOfArray https://docs.mongodb.com/manual/reference/operator/aggregation/indexOfArray/ and $range https://docs.mongodb.com/manual/reference/operator/aggregation/range/,那么它可能看起来更长,但实际上最有效$redact https://docs.mongodb.com/manual/reference/operator/aggregation/redact/:
db.getCollection('collection').aggregate([
{ "$match": {
"array": {
"$elemMatch": { "field": "BCD", "enabled": "true" },
}
}},
{ "$redact": {
"$cond": {
"if": {
"$lte": [
{ "$arrayElemAt": [
{ "$map": {
"input": {
"$filter": {
"input": {
"$map": {
"input": {
"$zip": {
"inputs": [
"$array",
{ "$range": [0, { "$size": "$array" }] }
]
}
},
"as": "a",
"in": {
"field": { "$arrayElemAt": [ "$$a.field", 0 ] },
"enabled": { "$arrayElemAt": [ "$$a.enabled", 0 ] },
"index": { "$arrayElemAt": [ "$$a", 1 ] }
}
}
},
"as": "a",
"cond": {
"$and": [
{ "$eq": [ "$$a.field", "BCD" ] },
{ "$eq": [ "$$a.enabled", "true" ] }
]
}
}
},
"as": "a",
"in": "$$a.index"
}},
0
]},
{ "$indexOfArray": [ "$array.enabled", "true" ] }
]
},
"then": "$$KEEP",
"else": "$$PRUNE"
}
}}
])
因此,确实没有实际的查询操作来强制执行此操作,但这两种情况都将选择保留在“服务器上”,而不是通过线路将数据发送到客户端然后进行过滤。
因为如果你这样做,它首先就否定了使用数据库的目的。所以你确实希望这发生在服务器上。