lanrete
lanrete

Reputation: 127

Querying a documents with nested array in mongoDB

EDIT: Below query were executed from DataGrip, mongodb version 4.2.6

I am fairly new to mongoDB and I am digging through a lot of documents but couldn't figure out how this would work.

My collections is like this:

db.cards.insertMany([
{
  "Name": "SingleFaced Card",
  "Face": [
    {"Type": "Front", "Color": ["Black"]},
  ]
},
{
  "Name": "DoubleFaced Card",
  "Face": [
    {"Type": "Front", "Color": ["Black"]},
    {"Type": "Back", "Color": ["Red", "Yellow"]}
  ]
},
]);

I would like to query the card, that has at least one face with the given color, say Red.

I have tried lots of different options, all of them give me a count of 0.

db.cards.count({"Face.Color": "Red"}); // 0 record
db.cards.count({"Face.Color": ["Red"]}) // 0 record
db.cards.count({"Face.Color": {$elemMatch:{$in:['Red']}}}) // 0 record
db.cards.count({"Face.Color": {$elemMatch:{$all:['Red']}}}) // 0 record
db.cards.count({"Face.Color": {$elemMatch:{$elemMatch:{$in:['Red']}}}}); // 0 record

I initially thought there is something wrong with my installation, but the below queries on nested fields worked.

db.cards.count({"Face.Type" : "Front"}); // 2 record
db.cards.count({"Face.Type" : "Back"}); // 1 record

Any suggestions on how should I make this work? Am I using the wrong design choice here?

Upvotes: 0

Views: 590

Answers (1)

thammada.ts
thammada.ts

Reputation: 5245

Your third query already works

db.cards.count({ "Face.Color": { $elemMatch: { $in: ['Red'] } } }) 

Upvotes: 2

Related Questions