【问题标题】:MongoDB positional operator with nested arrays带有嵌套数组的 MongoDB 位置运算符
【发布时间】:2017-01-15 01:52:05
【问题描述】:

样本集合结构:

{
"_id" : ObjectId("57cfd62001ca2dd672cfebb1"),
"name" : "Category",
"parent" : ObjectId("57cfd5d101ca2dd672cfebb0"),
"posts" : [
    {
        "name" : "Post",
        "author" : ObjectId("57cfd09401ca2dd672cfebac"),
        "content" : "Some content.",
        "comments" : [
            {
                "author" : ObjectId("57cfd09401ca2dd672cfebab"),
                "content" : "First comment",
                "rating" : 2
            },
            {
                "author" : ObjectId("57cfd09401ca2dd672cfebac"),
                "content" : "Second comment",
                "rating" : 5
            }
        ]
    }
]
}

我想选择authorObjectId("57cfd09401ca2dd672cfebab") 的所有comments

此查询正在运行,

db.categories.find({ 'posts.comments.author':ObjectId("57cfd09401ca2dd672cfebab") })

但我只想返回带有位置运算符的第一个匹配注释。像这样的东西是行不通的。 MongoDB 是否支持嵌套数组的位置运算符?

db.categories.find({ 'posts.comments.author': ObjectId("57cfd09401ca2dd672cfebab") }, 
{ 'posts.comments.$': 1 })

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    你有两个以上的嵌套级别...find() 可能不起作用,而是尝试聚合:-

    > db.categories.aggregate([{$unwind:"$posts"},{$unwind:"$posts.comments"},
    {$match:{"posts.comments.author":ObjectId("57cfd09401ca2dd672cfebab")}},
    {$project:{_id:0,"posts.comments":1}}]).pretty()
    

    输出:

    {
            "posts" : {
                    "comments" : {
                            "author" : ObjectId("57cfd09401ca2dd672cfebab"),
                            "content" : "First comment",
                            "rating" : 2
                    }
            }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-03-06
      • 1970-01-01
      • 1970-01-01
      • 2013-01-29
      • 1970-01-01
      • 2014-12-27
      • 2019-05-20
      • 2021-07-26
      相关资源
      最近更新 更多