agarcian
agarcian

Reputation: 3965

Querying a MongoDB collection with documents containing an array of (sub)documents where ALL documents in the array match a condition

Say you have a mongoDB collection called comments that contains documents like this:

{
    "_id" : ObjectId("55fc4e8f2b21ff102bb20d94"),
    "userName" : "user0053",
    "comment" : [ 
        {
            "timestamp" : ISODate("2015-09-18T17:49:03.678Z"),
            "title" : "Some title XYZ",
            "status" : "Approved",
            "content" : "blah blah blah"
        }, 
        {
            "timestamp" : ISODate("2015-09-18T17:49:03.678Z"),
            "title" : "Some nice looking title",
            "status" : "Approved",
            "content" : "blah blah blah"
        }, 
        {
            "timestamp" : ISODate("2015-09-18T17:49:03.678Z"),
            "title" : "A title",
            "status" : "Spam",
            "content" : "blah blah blah"
        }
    ]
}

The comment element is an array of documents, each containing several elements, among those a status with 3 (or any) possible values, say Approved, Spam, PendingReview.

I want to query all the documents in the collection whose comment element contains an array in which ALL documents have a status of say "Approved".

In the example above, the document does not qualify because there is at least one comment element that has a status different to Approved.

I believe this cannot be done with the $all and $elemMatch options, but it would need to be done with an Aggregate pipeline. I just haven't been able to figure out how.

Upvotes: 0

Views: 77

Answers (1)

Ori Dar
Ori Dar

Reputation: 19000

At it's simplest form, this can be achieved with $nin.

db.collection.find({"comment.status" : {$nin : ["Spam" , "PendingReview"]}})

Upvotes: 1

Related Questions