简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM