Mongodb 嵌套文档 where 子句 returns 许多子文档

Mongodb nested document where clause returns many subdocuments

我有一份 mongodb 文档,看起来与此类似:

{
"id": 1,
"title": "This is the title",
"body" : "This is the body",
"comments": [
    {
        "email_address": "mirko.benedetti@somemail.com",
        "name": "Mirko",
        "surname": "Benedetti",
        "language": "it",
        "text": "This is a message",
        "published": "Y",
        "on": "2014-03-22 15:04:04"
    },
    {
        "email_address": "marc.surname@somemail.com",
        "name": "Marc",
        "surname": "Surname",
        "language": "it",
        "text": "Another Message",
        "published": "N",
        "on": "2014-03-23 15:04:05"
    }
  ]
}

我有这样的查询:

$this->db->collection->find(array('id' => $id, 'language' => $lang, 'comments.published' => 'Y'),
                        array('comments.name' => 1, 'comments.surname' => 1, 'comments.text' => 1, 'comments.on' => 1, '_id' => 0));

我的问题是 运行ning 那个查询,mongodb returns 两个评论,我不想要,我只想要带有 "published" 的消息: "Y".

例如,我尝试选择 运行 'comments.published' => 'something' 和 none 评论,这是正确的,但如果至少有一个评论有 标记 "published" 设置为 'Y',显示两条评论。

欢迎任何帮助。

看看$elemMatch documentation

db.schools.find( { zipcode: "63109" },
                 { students: { $elemMatch: { school: 102 } } } )

使用 elemMatch 运算符时需要小心。首先它有两个变体。 $elemMatch(projection) & $elemMatch(query)

elemMatch(projection) 变体似乎有效,因为您拥有的过滤条件仅与评论数组中的一个值匹配。

下面的查询可以正常工作。

find({'_id' : ObjectId("582f2abf9b549b5a765ab380"), comments: { $elemMatch: { language: "it", published : "Y" }}})

现在考虑当评论数组中有超过 1 个匹配值(两个值具有 'Y' 已发布状态)时,上述查询将不起作用,只会 return 第一个匹配值.

在这种情况下,您将需要使用 $filter,它将根据传递的筛选条件筛选评论数组。

aggregate([{
    $match: {
        '_id': ObjectId("582f2abf9b549b5a765ab380")
    }
}, {
    "$project": {
        "comments": {
            "$filter": {
                "input": "$comments",
                "as": "result",
                "cond": {
                    $and: [{
                        $eq: ["$$result.language", "it"]
                    }, {
                        $eq: ["$$result.published", "Y"]
                    }]
                }
            }
        }
    }
}, {
    $project: {
        "comments": {
            name: 1,
            surname: 1,
            text: 1,
            on: 1
        }
    }
}])