ABB
ABB

Reputation: 53

Check if a field exists in all the elements of an array in MongoDB and return the documents that contain it

For a sample document like below

{
 "_id" : ObjectId("58f5ae159dfbbf2c98041952"),
 "patient" : {
  "drug" : [ 
 {
    "drugstartdate" : "20151007",
    "actiondrug" : "1",
    "openfda": {
     //some fields here
    }
 },
 {
  //details of one more drug that may or may not contain openfda field
 }
 ]
},
{//Second report
},.....

how to return documents(reports) that contain "openfda" sub-document for all the drug elements in drug array? Tried the following:

db.getCollection('collname').find({"patient.drug":
{$elemMatch:{"openfda":
{$exists:true}
}
}
})

$elemMatch will return all reports where atleast one drug contains "openfda" field. Also tried:

db.getCollection('BigFDAData_05_06').find({"patient.drug":
{$all:["openfda"]}})

But the above returns nothing. What is the right way to achieve this?

Upvotes: 2

Views: 9363

Answers (1)

s7vr
s7vr

Reputation: 75924

You can use $elemMatch query operator. There is no direct query operator to address your case.

db.collname.find( { "patient.drug":  { $not: { $elemMatch: { openfda: {$exists:false} } } } } )

"$elemMatch" + "$exists:false"

This part includes all the documents where patient.drug array don't have at least one openfda embedded document.

$not

This part will keep the all the documents which are not in "$elemMatch" + "$exists:false".

These are all the documents that has its all drugs array have openfda embedded doc.

Upvotes: 7

Related Questions