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


mongo find documents where subdocument matches multiple criteria

我有一个类似的集合

{ 
"_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其中(arrWhoHasRead.nUserID=577b0b8d41140640f94894a1 AND arrWhoHasRead.strRole="Author")

我试着在一个数组中嵌套我的多个AND条件(Paradishesion中的那个),但这似乎没有多大帮助。也许我需要投影?

我在PHP 中使用这个

如果您想显示所有符合您要求的记录,包括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"
    }]
}

如果你只想在结果中有与ObjectId("577b0b8d41140640f94894a1")匹配的arrWhoHasRead元素,你可以做aggregate,但不需要投影,除非你想排除其他字段:

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&与arrWhoHasRead 中的ObjectId("577b0b8d41140640f94894a1")一样多的记录