Home > Net >  How to write a query in mongo db to find elements in which the nested array does not have an element
How to write a query in mongo db to find elements in which the nested array does not have an element

Time:07-22

There is a given array with data .

[
   {
      "_id":"62d9553f2f7d45d51e9e6850",
      "title":"lol",
      "body":"lol",
      "readIds":[
         {
            "id":"62c56b2cffe059fdfdd19230",
            "createdAt":1658417024700
         }
      ],
      "mode":"custom",
      "createdAt":"2022-07-21T13:31:43.633Z",
      "updatedAt":"2022-07-21T15:23:44.701Z"
   },
   {
      "_id":"62d954e2ea35817546d42702",
      "title":"tesssst",
      "body":"tesssst",
      "readIds":[
      ],
      "mode":"custom",
      "createdAt":"2022-07-21T13:30:10.759Z",
      "updatedAt":"2022-07-21T13:30:10.759Z"
   },
]

And I need to write a query to filter the array and get only those elements which readIds hasn't object with id equal to '62c56b2cffe059fdfdd19230'. My attempts were like this:

  .find({
            readIds: {
              $elemMatch: {
                id: {
                  $not: {
                    $eq: id,
                  },
                },
              },
            },
          })

CodePudding user response:

I'm not sure i got your question correctly, but isn't the following working?

db.getCollection('stuff').find({"readIds.id": {$ne: "62c56b2cffe059fdfdd19230"}})

you can test it here: Mongo Playground

  • Related