Mongodb 对内部文档数组使用带有 $eq 和 $arrayElemAt 的编辑
Mongodb using redact with $eq and $arrayElemAt for the inner document array
我的文档结构如下:
{
"_id" : ObjectId("57c93af8bf501124df658a0e"),
"friends" : [
{ "userid" : 14, "xxxx" : "xxx" },
{ "userid" : 13, "xxx" : "xxx" }
]
},{
"_id" : ObjectId("57c93af8bf501124df658a0e"),
"friends" : [
{ "userid" : 1, "xxxx" : "xxx" },
{ "userid" : 14, "xxx" : "xxx" }
]
}
我需要在 friends 数组的最后一个元素中检索用户 ID 为 14 的文档。所需的输出如下:
{
"_id" : ObjectId("57c93af8bf501124df658a0e"),
"friends" : [
{ "userid" : 14, "xxx" : "xxx" }
]
}
我尝试按照建议use the $slice operator to get last element of array in mongodb;但我需要在子文档上执行此操作。
如何使用 -1 处的“$arrayElemAt”在 $redact 中将 "friends.user" $eq 的查询结构化为 14?
运行 以下聚合管道以获得所需的结果:
db.collection.aggregate([
{ "$match": { "friends.userid": 14 } },
{
"$redact": {
"$cond": {
"if": { "$eq": [{ "$arrayElemAt": [ "$friends.userid", -1 ] }, 14 ] },
"then": "$$KEEP",
"else": "$$PRUNE"
}
}
}
])
我的文档结构如下:
{
"_id" : ObjectId("57c93af8bf501124df658a0e"),
"friends" : [
{ "userid" : 14, "xxxx" : "xxx" },
{ "userid" : 13, "xxx" : "xxx" }
]
},{
"_id" : ObjectId("57c93af8bf501124df658a0e"),
"friends" : [
{ "userid" : 1, "xxxx" : "xxx" },
{ "userid" : 14, "xxx" : "xxx" }
]
}
我需要在 friends 数组的最后一个元素中检索用户 ID 为 14 的文档。所需的输出如下:
{
"_id" : ObjectId("57c93af8bf501124df658a0e"),
"friends" : [
{ "userid" : 14, "xxx" : "xxx" }
]
}
我尝试按照建议use the $slice operator to get last element of array in mongodb;但我需要在子文档上执行此操作。
如何使用 -1 处的“$arrayElemAt”在 $redact 中将 "friends.user" $eq 的查询结构化为 14?
运行 以下聚合管道以获得所需的结果:
db.collection.aggregate([
{ "$match": { "friends.userid": 14 } },
{
"$redact": {
"$cond": {
"if": { "$eq": [{ "$arrayElemAt": [ "$friends.userid", -1 ] }, 14 ] },
"then": "$$KEEP",
"else": "$$PRUNE"
}
}
}
])