Ven Nilson
Ven Nilson

Reputation: 1019

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.

Upvotes: 5

Views: 1615

Answers (1)

J.F.
J.F.

Reputation: 15187

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.

Upvotes: 2

Related Questions