Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB delete embedded documents through array of Ids

I am working on a Node.js application that is using a MongoDB database with Mongoose. I've been stuck in this thing and didn't come up with the right query.

Problem:

There is a collection named chats which contain embedded documents (rooms) as an array of objects. I want to delete these embedded documents (rooms) through Ids which are in the array.

  {
    "_id": "ObjectId(6138e2b55c175846ec1e38c5)",
    "type": "bot",
    "rooms": [
      {
        "_id": "ObjectId(6138e2b55c145846ec1e38c5)",
        "genre": "action"
      },
      {
        "_id": "ObjectId(6138e2b545c145846ec1e38c5)",
        "genre": "adventure"
      }
    ]
  },
  {
    "_id": "ObjectId(6138e2b55c1765846ec1e38c5)",
    "type": "person",
    "rooms": [
      {
        "_id": "ObjectId(6138e2565c145846ec1e38c5)",
        "genre": "food"
      },
      {
        "_id": "ObjectId(6138e2b5645c145846ec1e38c5)",
        "genre": "sport"
      }
    ]
  },
  {
    "_id": "ObjectId(6138e2b55c1765846ec1e38c5)",
    "type": "duo",
    "rooms": [
      {
        "_id": "ObjectId(6138e21c145846ec1e38c5)",
        "genre": "travel"
      },
      {
        "_id": "ObjectId(6138e35645c145846ec1e38c5)",
        "genre": "news"
      }
    ]
  }

I am converting my array of ids into MongoDB ObjectId so I can use these ids as match criteria.

const idsRoom = [
  '6138e21c145846ec1e38c5',
  '6138e2565c145846ec1e38c5',
  '6138e2b545c145846ec1e38c5',
];

const objectIdArray = idsRoom.map((s) => mongoose.Types.ObjectId(s));

and using this query for the chat collection. But it is deleting the whole document and I only want to delete the rooms embedded document because the ids array is only for the embedded documents.

Chat.deleteMany({ 'rooms._id': objectIdArray }, function (err) {
  console.log('Delete successfully')
})

I really appreciate your help on this issue.

like image 766
Ven Nilson Avatar asked Nov 06 '22 00:11

Ven Nilson


1 Answers

You have to use $pull operator in a update query like this:

This query look for documents where exists the _id into rooms array and use $pull to remove the object from the array.

yourModel.updateMany({
  "rooms._id": {
    "$in": [
      "6138e21c145846ec1e38c5",
      "6138e2565c145846ec1e38c5",
      "6138e2b545c145846ec1e38c5"
    ]
  }
},
{
  "$pull": {
    "rooms": {
      "_id": {
        "$in": [
          "6138e21c145846ec1e38c5",
          "6138e2565c145846ec1e38c5",
          "6138e2b545c145846ec1e38c5"
        ]
      }
    }
  }
})

Example here.

Also you can run your query without the query parameter (in update queries the first object is the query) like this and result is the same. But is better to indicate mongo the documents using this first object.

like image 155
J.F. Avatar answered Nov 15 '22 05:11

J.F.