jones
jones

Reputation: 1453

Mongodb how to move specific object from array to another array?

Suppose I have the following collection:

{  
  "_id":ObjectId("562e7c594c12942f08fe4192"),
  "first":[  
    {  
      "shape":"square",
      "color":"blue"
    },
    {  
      "shape":"circle",
      "color":"red"
    }
  ],
  "second": []
}

What I want to do is, first find a specific object inside the first array and move that to second field

db.collection.findOneAndUpdate({_id: ObjectId("562e7c594c12942f08fe4192")}, {$pull: {first: {color: "red"}}, $push: {// that specific object to second array}})

Upvotes: 1

Views: 266

Answers (2)

dnickless
dnickless

Reputation: 10918

This cannot be done in a single operation. You can do this instead, though:

MyModel.findOne({ _id: ObjectId("562e7c594c12942f08fe4192"), "first.color": "red" }, 'first.$', function (err, doc) {
    MyModel.findByIdAndUpdate(ObjectId("562e7c594c12942f08fe4192"), {
        $pull: { first: { color: "red" } },
        $push: { second: doc.first[0] }
    }, function (err, docs) {  })
});

Upvotes: 2

Jack
Jack

Reputation: 3057

Try this using cursors.

db.getCollection('test')
    .find({_id: ObjectId("562e7c594c12942f08fe4192")})
    .forEach(function(doc) {
        doc.second = doc.first.filter(function(x) { return x.color === "blue"});
        doc.first = doc.first.filter(function(x) { return x.color !== "blue" });
        db.getCollection('test').save(doc)
    }
)

Replace "blue" with your chosen item.

This will however work for your example but will remove any previous items in second.

If you just want to append it this should work.

db.getCollection('test')
    .find({_id: ObjectId("562e7c594c12942f08fe4192")})
    .forEach(function(doc) {
         doc.second = doc.second.concat((doc.first.filter((x) => x.color === "green")));
         doc.first = doc.first.filter(function(x) { return x.color !== "green" });
         db.getCollection('test').save(doc)
      }
)

Upvotes: 0

Related Questions