具有嵌套数组的MongoDB位置运算符

时间:2016-09-07 11:31:32

标签: mongodb

样品采集结构:

{
"_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
            }
        ]
    }
]
}

我想选择commentsauthor的所有ObjectId("57cfd09401ca2dd672cfebab")

此查询正常,

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

但我想只返回第一个与位置运算符匹配的注释。这样的事情不起作用。 MongoDB是否支持使用嵌套数组的位置运算符?

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

1 个答案:

答案 0 :(得分:0)

你有两个以上的嵌套级别...... 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
                }
        }
}