【问题标题】:Mongodb using redact with $eq and $arrayElemAt for the inner document arrayMongodb 对内部文档数组使用带有 $eq 和 $arrayElemAt 的编辑
【发布时间】:2016-09-02 09:24:58
【问题描述】:

我的文档结构如下:

{
    "_id" : ObjectId("57c93af8bf501124df658a0e"),
    "friends" : [
        {   "userid" : 14, "xxxx" : "xxx"   },
        {   "userid" : 13,  "xxx" : "xxx"   }
    ]
},{
    "_id" : ObjectId("57c93af8bf501124df658a0e"),
    "friends" : [
        {   "userid" : 1, "xxxx" : "xxx"    },
        {   "userid" : 14,  "xxx" : "xxx"   }
    ]
}

我需要在朋友数组的最后一个元素中检索用户 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?

【问题讨论】:

标签: mongodb mongodb-query aggregation-framework mongodb-java


【解决方案1】:

运行以下聚合管道以获得所需的结果:

db.collection.aggregate([
    { "$match": { "friends.userid": 14 } },
    { 
       "$redact": {
            "$cond": {
                "if": { "$eq": [{ "$arrayElemAt": [ "$friends.userid", -1 ] }, 14 ] },
                "then": "$$KEEP",
                "else": "$$PRUNE"
            }
        }
    } 
])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-20
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    • 1970-01-01
    • 1970-01-01
    • 2021-04-24
    • 1970-01-01
    相关资源
    最近更新 更多