Move different elements to another array in MongoDB?


Use forEach and check for the different elements and use save() along with some condition. Let us create a collection with documents −

> db.demo646.insertOne(
...    {
...
...       "Information": [
...          { id: 100, Name:"Chris" },
...          { id: 100, Name:"Chris" },
...          { id: 101, Name:"David" },
...          { id: 100, Name:"Chris" }
...       ],
...       "different": []
...    }
... )
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e9c82ec6c954c74be91e6ed")
}

Display all documents from a collection with the help of find() method −

> db.demo646.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5e9c82ec6c954c74be91e6ed"),
   "Information" : [
      {
         "id" : 100,
         "Name" : "Chris"
      },
      {
         "id" : 100,
         "Name" : "Chris"
      },
      {
         "id" : 101,
         "Name" : "David"
      },
      {
         "id" : 100,
         "Name" : "Chris"
      }
   ],
   "different" : [ ]
}

Following is the query to move elements to another array −

> db.demo646.find({}).forEach(function(d) {
...    d.different = d.Information.filter(function(v) { return v.id == 101 })
...    d.Information = d.Information.filter(function(v) { return v.id != 101 })
...    db.demo646.save(d)
...    }
... )

Display all documents from a collection with the help of find() method −

> db.demo646.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5e9c82ec6c954c74be91e6ed"),
   "Information" : [
      {
         "id" : 100,
         "Name" : "Chris"
      },
      {
         "id" : 100,
         "Name" : "Chris"
      },
      {
         "id" : 100,
         "Name" : "Chris"
      }
   ],
   "different" : [
      {
         "id" : 101,
         "Name" : "David"
      }
   ]
}

Updated on: 12-May-2020

236 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements