MongoDB query - Nested Object

227 Views Asked by At

I am trying to retrieve all the documents where one of the value of the attribute in the nested object starts with "-". Below is the sample document - I want to search the "counts" array object and find if any of the "value" attribute in the nested object starts with "-"

{
  "_id": "XYZ",
  "departureDate": "2020-10-09",
  "travelerCounts": [
    {
      "counts": [
        {
          "key": "J",
          "value": "4"
        },
        {
          "key": "Y",
          "value": "4"
        }
      ],
      "travelCountType": "ActualCapacity"
    },
    ...
  ]
 },
 {
   "_id": "XYZ1",
  "departureDate": "2020-10-09",
  "travelerCounts": [
    {
      "counts": [
        {
          "key": "J",
          "value": "18"
        },
        {
          "key": "Y",
          "value": "-1"
        }
      ],
      "travelCountType": "ActualCapacity"
    }
    ...
  ]
 }

I have tried this but no luck -

db.myCollection.find(
{departureDate: "2020-10-09"},
{
    "travelerCounts": { 
        "$elemMatch": {
            "travelCountType": "ActualCapacity",
            "counts": {
                "$elemMatch": {
                    "value": { $regex : /^-/ }
                }
            }
        }
    }
})

Please help

1

There are 1 best solutions below

4
On

As state in the official MongoDB documentation:

If you specify only a single condition in the $elemMatch expression, and are not using the $not or $ne operators inside of $elemMatch, $elemMatch can be omitted. See Single Query Condition.

This works for retrieving all documents that at least one of its nested documents contains a value which starts with a dash:

collection.find({"departureDate": "2020-10-09", "travelerCounts.counts.value": {"$regex" : /^-/}})

In your example, you are using the projection parameter (second parameter in find method) for the filter, which is incorrect.

EDIT: The solution for retrieving all collection documents that at least have one document in the nested travelerCounts, that meets the following conditions:

  • travelCountType is "ActualCapacity".
  • counts contains at least one document whose value starts with a dash.

Query:

collection.find({"departureDate": "2020-10-09", "travelerCounts": {"$elemMatch": {"travelCountType": "ActualCapacity", "counts.value": {"$regex" : /^-/}}}})