mongo查找子文档匹配多个条件的文档

时间:2016-07-18 23:05:01

标签: php mongodb

我有一个类似于

的集合
{ 
"_id" : ObjectId("57832cb74114065710110971"), 
"strName" : "Some Book In Library", 
"strUPN" : "123456", 
"bHardCover": "yes",
"bIsDamaged" : "yes", 
"arrWhoHasRead" : [
    {
        "nUserID" : ObjectId("577b0b8d41140640f94894a1"), 
        "strPersonName" : "John Doe", 
        "strRole" : "Author"
    },
{
        "nUserID" : ObjectId("xyz"), 
        "strPersonName" : "Jane Doe", 
        "strRole" : "Customer"
    }
]
}

我想返回所有bIsDamaged = yes和bHardCover = yes的记录 AND where(arrWhoHasRead.nUserID = 577b0b8d41140640f94894a1 AND arrWhoHasRead.strRole =" Author")

我尝试将多个AND条件(在paranthesis中的那个)嵌套在一个数组中,但这似乎没什么帮助。也许我需要投影?

我在PHP中使用它

1 个答案:

答案 0 :(得分:0)

如果您想显示符合您要求的所有记录,包括arrWhoHasRead的所有其他元素,则find就足够了:

db.device.find({"bHardCover": "yes","bIsDamaged" : "yes","arrWhoHasRead.nUserID":ObjectId("577b0b8d41140640f94894a1"),"arrWhoHasRead.strRole":"Author"});

会给你:

{
    "_id": ObjectId("578d7f9aca19a63da3984899"),
    "strName": "Some Book In Library",
    "strUPN": "123456",
    "bHardCover": "yes",
    "bIsDamaged": "yes",
    "arrWhoHasRead": [{
        "nUserID": ObjectId("577b0b8d41140640f94894a1"),
        "strPersonName": "John Doe",
        "strRole": "Author"
    }, {
        "nUserID": ObjectId("578d7d6bca19a63da3984897"),
        "strPersonName": "Jane Doe",
        "strRole": "Customer"
    }]
} {
    "_id": ObjectId("578d7fb0ca19a63da398489a"),
    "strName": "Some Book In Library",
    "strUPN": "123456",
    "bHardCover": "yes",
    "bIsDamaged": "yes",
    "arrWhoHasRead": [{
        "nUserID": ObjectId("577b0b8d41140640f94894a1"),
        "strPersonName": "John Doe",
        "strRole": "Author"
    }, {
        "nUserID": ObjectId("578d7d6bca19a63da3984898"),
        "strPersonName": "Jane Doe",
        "strRole": "Customer"
    }]
}

如果您希望结果只包含arrWhoHasRead匹配ObjectId("577b0b8d41140640f94894a1")的元素,您可以执行aggregate但不需要投影,除非您想要排除其他字段:< / p>

db.device.aggregate([{
    "$unwind": "$arrWhoHasRead"
}, {
    $match: {
        "bHardCover": "yes",
        "bIsDamaged": "yes",
        "arrWhoHasRead.nUserID": ObjectId("577b0b8d41140640f94894a1"),
        "arrWhoHasRead.strRole": "Author"
    }
}])

将给出:

{
    "_id": ObjectId("578d7f9aca19a63da3984899"),
    "strName": "Some Book In Library",
    "strUPN": "123456",
    "bHardCover": "yes",
    "bIsDamaged": "yes",
    "arrWhoHasRead": {
        "nUserID": ObjectId("577b0b8d41140640f94894a1"),
        "strPersonName": "John Doe",
        "strRole": "Author"
    }
} {
    "_id": ObjectId("578d7fb0ca19a63da398489a"),
    "strName": "Some Book In Library",
    "strUPN": "123456",
    "bHardCover": "yes",
    "bIsDamaged": "yes",
    "arrWhoHasRead": {
        "nUserID": ObjectId("577b0b8d41140640f94894a1"),
        "strPersonName": "John Doe",
        "strRole": "Author"
    }
}

请注意,数组已经展开,因此arrWhoHasRead&amp;中只有json对象。与ObjectId("577b0b8d41140640f94894a1")

中的arrWhoHasRead一样多的记录