0

I want to return all values in the array that match the criteria.

but when I query, It returns only one result.

This is the value of my DB.

[{
    "channel": "a",
    "video": [
        {
            "name": 1
            "status": ''
        },
        {
            "name": 2
            "status": 'err'
        },
        {
            "name": 3
            "status": 'err'
        }
    ]
},
{
    "channel": "b",
    "video": [
        {
            "name": 4
            "status": 'err'
        },
        {
            "name": 5
            "status": 'err'
        },
        {
            "name": 6
            "status": ''
        }
    ]
}]

I want a get result like this

[
{
    "channel": "a",
    "video": [
        {
            "name": 2
            "status": 'err'
        },
        {
            "name": 3
            "status": 'err'
        }
    ]
},
{
    "channel": "b",
    "video": [
        {
            "name": 4
            "status": 'err'
        },
        {
            "name": 5
            "status": 'err'
        }
    ]
}
]

but when I using my code

var errData = await DB.find({
            'video.status' : { $in : 'err' }
        }, 
        {
            'channel': true,
            'video' : {
                $elemMatch : {
                    'status': { $in : 'err' }
                }
            }
        } )

it returns like this

[
{
    "channel": "a",
    "video": [
        {
            "name": 2
            "status": 'err'
        }
    ]
},
{
    "channel": "b",
    "video": [
        {
            "name": 4
            "status": 'err'
        }
    ]
},
]

how can I fix it in mongoose(don't use aggregate)?

If it is impossible without using an aggregate, how can I make it by using an aggregate?

would you please help me?

dhShin
  • 21
  • 4

1 Answers1

1

As docs explain:

The $elemMatch operator limits the contents of an field from the query results to contain only the first element matching the $elemMatch condition

That's why you get only one element for each document.

Also, it seems (look here) that is not possible without aggregation.

Using aggregation you can use $filter in this way:

db.collection.aggregate([
  {
    "$set": {
      "video": {
        "$filter": {
          "input": "$video",
          "as": "v",
          "cond": {"$eq": ["$$v.status","err"]}
        }
      }
    }
  }
])

Example here

J.F.
  • 13,927
  • 9
  • 27
  • 65