mongodbrobo3t

Query for remove object inside array using gte condition MonggoDB


Hello I'm new to monggodb query, I'm trying to delete object inside my array using mongo3t query which is the date going forward from 2021-09-13.

My current data is: attendance

{
    "_id": {
        "$oid": "6070b991d6231f8c205cb093"
    },
    "UserId": "5",
    "Ranges": [
        {
            "DateFrom": {
                "DateTime": {
                    "$date": "2021-09-12T00:00:00.000Z"
                },
                "Ticks": {
                    "$numberLong": "637536960000000000"
                }
            }
        },
        {
            "DateFrom": {
                "DateTime": {
                    "$date": "2021-09-13T00:00:00.000Z"
                },
                "Ticks": {
                    "$numberLong": "637536960000000000"
                }
            }
        },
        {
            "DateFrom": {
                "DateTime": {
                    "$date": "2021-09-15T00:00:00.000Z"
                },
                "Ticks": {
                    "$numberLong": "637536960000000000"
                }
            }
        }
    ]
}

Here's the query I tried to execute,

db.getCollection('attendance').update(
    { UserId: "5" },
    { $pull: { 'Ranges': { DateFrom: { DateTime: { $gte: new Date(2021, 09, 13) } } } } }
);

My query runs successfully with message "Updated 1 existing record(s) in 4ms", but upon checking the data nothing happens.


Solution

  • This seems ok, removed only the last element.

    Query

    Test code here

    db.collection.update({
      UserId: "5"
    },
    {
      $pull: {
        Ranges: {
          "DateFrom.DateTime": {
            $gte: ISODate("2021-09-14T00:00:00.000Z")
          }
        }
      }
    })