Patrick Ian Co
Patrick Ian Co

Reputation: 345

MongoDB - Query Array of Documents

Hi I currently have a collection with documents that look like this

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

So if I do a query using

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

This document shown above should not return since I want to get all of the documents with the following condition: Documents that has a faculty_number of 111 and status of Sent

Upvotes: 0

Views: 44

Answers (1)

mickl
mickl

Reputation: 49985

$elemMatch is what you need, this operator will check both conditions on each document of recipients array

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

Upvotes: 1

Related Questions