Domanda

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

È stato utile?

Soluzione

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"}}])
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top