0

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?

1 Answer 1

2

Your third query already works

db.cards.count({ "Face.Color": { $elemMatch: { $in: ['Red'] } } }) 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the link! I did some comparison on the environment. I was running the examples through DataGrip from JetBrain on mongodb 4.2.6. I have downgraded the db version to 4.2.5 and re-run the query from python package pymongo and it works now. Perhaps there is a bug on either DataGrip or version 4.2.6

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.