1

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}})

2 Answers 2

2

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) {  })
});
Sign up to request clarification or add additional context in comments.

Comments

0

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)
      }
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.