Move different elements to another array in MongoDB?

To move different elements to another array in MongoDB, use forEach with filter() methods to separate elements based on criteria and save() to update the document. This approach allows you to move specific elements from one array to another within the same document.

Syntax

db.collection.find({}).forEach(function(doc) {
    doc.targetArray = doc.sourceArray.filter(function(element) { 
        return condition; 
    });
    doc.sourceArray = doc.sourceArray.filter(function(element) { 
        return !condition; 
    });
    db.collection.save(doc);
});

Sample Data

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 Initial Data

db.demo646.find().pretty();
{
    "_id": ObjectId("5e9c82ec6c954c74be91e6ed"),
    "Information": [
        {
            "id": 100,
            "Name": "Chris"
        },
        {
            "id": 100,
            "Name": "Chris"
        },
        {
            "id": 101,
            "Name": "David"
        },
        {
            "id": 100,
            "Name": "Chris"
        }
    ],
    "different": []
}

Move Elements to Different 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);
});

Verify Result

db.demo646.find().pretty();
{
    "_id": ObjectId("5e9c82ec6c954c74be91e6ed"),
    "Information": [
        {
            "id": 100,
            "Name": "Chris"
        },
        {
            "id": 100,
            "Name": "Chris"
        },
        {
            "id": 100,
            "Name": "Chris"
        }
    ],
    "different": [
        {
            "id": 101,
            "Name": "David"
        }
    ]
}

How It Works

  • filter() creates new arrays based on the condition
  • Elements with id == 101 move to the "different" array
  • Elements with id != 101 remain in the "Information" array
  • save() persists the changes to the document

Conclusion

Use forEach with filter methods to conditionally move array elements between fields in MongoDB documents. This approach effectively separates elements based on specific criteria while maintaining data integrity.

Updated on: 2026-03-15T03:15:44+05:30

374 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements