1

I have a collection with documents are like this:

{
    "date" : 20200817,
    "items" : [ 
        {
            "name" : "item1", "values" : ["val1", "val2", "val3", "val4"]
        }, 
        {
            "name" : "item2", "values" : ["val1", "val4"]
        }, 
        {
            "name" : "item3", "values" : ["val1", "val3"]
        }
    ]
}

I want to get list of name of items that val3 is exist in values like this

['item1', 'item3']

I have this query :

db.test.find({
    'dateM': 20200817,
    'items': {
        '$elemMatch':{
            'values':{
                '$elemMatch':{
                    $in:['val3']
                }
            }
         }
     }
}, {'lists.name': 1})

but i get list of name of all items.

Where is my query wrong?

What can I do?

Thanks

0

2 Answers 2

1

You need to use aggregation there. This is one way you can achieve

[
  {
    $project: {
      output: {
        $map: {
          input: {
            $filter: {
              input: "$items",
              cond: {
                $in: [
                  "val3",
                  "$$this.values"
                ]
              }
            }
          },
          in: "$$this.name"
        }
      }
    }
  }
]

Working Mongo playground

Sign up to request clarification or add additional context in comments.

Comments

0

The query you have should return only documents that contain at least one item with val3.

If returning only the first matching element is sufficient, you use the projection form of $elemMatch, otherwise, you will need to either use aggregation or filter the array on the client side.

Comments

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.