MongoDB - 查询文档数组

时间:2018-01-17 17:50:43

标签: mongodb

您好我目前有一个包含这样的文档的集合

 {
    "_id" : ObjectId("5a5f814487c320156094c144"),
    "sender_id" : "123",
    "iso_number" : "ABC-DEF-123",
    "subject" : "Sample Memo",
    "content" : "This is a sample memorandum sent through postman.",
    "recipients" : [ 
        {
            "faculty_number" : 222,
            "_id" : ObjectId("5a5f814487c320156094c146"),
            "status" : "Sent"
        }, 
        {
            "faculty_number" : 111,
            "_id" : ObjectId("5a5f814487c320156094c145"),
            "status" : "Seen"
        }
    ],
    "memo_created" : ISODate("2018-01-17T17:00:52.104Z"),
    "__v" : 0
}

所以,如果我使用

进行查询

db.collection.find({"recipients.faculty_number": 111, "recipients.status": "Sent"})

上面显示的文档不应该返回,因为我想获得具有以下条件的所有文档: faculty_number为111且状态为已发送

的文档

1 个答案:

答案 0 :(得分:1)

$elemMatch就是您所需要的,此运算符将检查recipients数组

的每个文档的两个条件
db.collection.find({"recipients": { $elemMatch: { "faculty_number": 111, "status": "Sent"} }})