Simone Carletti
Simone Carletti

Reputation: 176412

Search for records where one item in an array contains an attribute

I have a collection containing documents. Each document has a part attribute containing an Array of Hash (documents). These documents may or may not have a _encwas attribute.

{ 
  _id : "00001",
  parts : [
    { _encwas: 1, body: "" },
    { body: "" }
  ]
},
{ 
  _id : "00002",
  parts : [
    { _encwas: 1, body: "" },
    { _encwas: 2, body: "" }
  ]
},
{ 
  _id : "00003",
  parts : [
    { body: "" },
    { body: "" }
  ]
}

Is there a quick way to find all records where at least one part contains a _encwas attribute?

The following query works

db.collection.find({ "parts.0._encwas" : { $exists : true } });

but I would love to find a way to replace 0 with any part. For example

db.collection.find({ "parts.*._encwas" : { $exists : true } });

The query should be as efficient as possible (I don't mind if I need to create additional indexes) because I need to iterate more than 1M records.

Upvotes: 1

Views: 673

Answers (1)

RLI123
RLI123

Reputation: 487

This seemed to work when I tried with your test data:

db.collection.find( { "parts._encwas": { $exists : true } } )

Moreover, you can find all documents containing _encwas having a specific value using:

db.collection.find( { "parts._encwas": 4 } )

...where 4 is the value...

I believe the relevant part of the documentation is here: Dot Notation

Upvotes: 3

Related Questions