2

I have a database with documents like

{_id: 5,
 fruit: 'apple',
 vitamins: ['B1', 'B12', 'A1']
}
{_id: 7,
 fruit: 'appricot',
 vitamins: ['B6', 'D12', 'A1']
}

Is there a way to query for all the records which have e.g. vitamin 'A1'?

I am looking for a mongo shell query and a pymongo equivalent. I know that I can put a for loop to iterate over records and check whether the list contains an element or no, but I prefer a query if there is one.

As it is a list and not a list of objects so seems I can't use $elemMatch...

Thanks

3
  • A simple find query like db.collection.find({"vitamins":"A1"}) should work just fine. Did you try it? Commented May 6, 2014 at 17:05
  • of course I did, it doesn't work... With the query you wrote, I expect to get the records which have "vitamins":"A1", exactly "A1" and nothing more. Commented May 6, 2014 at 17:15
  • Got it. You have 2 options: 1) Use the index in the projection like db.collection.find({"vitamins":"A1"}, {"fruit":1, "vitamins.$":1}) 2) Aggregation framework Commented May 6, 2014 at 17:19

1 Answer 1

2

You have a couple of options:

Option 1: If you want to match just one element, you could use the index in projection

db.collection.find({"vitamins":"A1"}, {"fruit":1, "vitamins.$":1})

Option 2: If you want to able to match multiple elements in the array, you can look at the aggregation framework:

db.collection.aggregate([{$unwind:"$vitamins"}, {$match:{"vitamins":"A1"}}])
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Anand! Tried Option 1, works fine. Still need to read more about the aggregation framework, I don't yet understand it properly.

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.