MongoDB: multiple $elemMatch

后端 未结 2 1261
南方客
南方客 2020-12-31 11:26

I have MongoDB documents structured like this:

{_id: ObjectId(\"53d760721423030c7e14266f\"),
fruit: \'apple\',
vitamins: [
    {
     _id: 1,
     name: \'B7         


        
2条回答
  •  粉色の甜心
    2020-12-31 12:13

    In this case you can use the $and-operator .

    Try this query:

    find({
        $and: [
             {'vitamins': {'$elemMatch': {'name': 'A1', 'state': 'non_free'} } },
             {'vitamins': {'$elemMatch': {'name': 'B7', 'state': 'free'} } }
        ]
    });
    

    To explain why you received only the result matching the second criteria: The objects inside each {} you pass to MongoDB are key/value pairs. Each key can only exist once per object. When you try to assign a value to the same key twice, the second assignment will override the first. In your case you assigned two different values to the key $elemMatch in the same object, so the first one was ignored. The query which actually arrived in MongoDB was just find({'vitamins': {'$elemMatch': {'name': 'B7', 'state': 'free'}}}).

    Whenever you need to apply the same operator to the same key twice, you need to use $or or $and.

提交回复
热议问题