Expressjs & MongoDB 更新集合数组中的对象

Expressjs & MongoDB update object in collection's array

我想更新集合的数组,我在集合的数组中查找对象并将新值推送到对象时遇到问题,我尝试了一些东西,但似乎我无法在数组上使用集合方法?

router.post('/mountain_rescue_update', function(req, res) {
  var collection = db.collection('rescuemodels');
  var id = req.body.id;

  collection.update({"type": "FeatureCollection"},function (err, doc) {
     if (doc) {
         doc.find({"features": []}, function (err, result) {
             if (err) throw err;

             res.send(result);
         });
     }
   });
    }); 

在 FeatureCollection 中我有数组特征,我想在该数组上执行 find 方法并通过 id 查找对象,然后在可能的情况下进行推送。

实际上如何查找数组?因此可以在该数组上完成一些操作,如查找和更新。我现在那个表达式的特点是:[] 看起来不正确,但我不知道如何找到它。

我试过这样的东西

collection.find({"features":{"properties":{"date":id}}}, function(err,doc){
     console.log(doc);
  }

如果集合中有一个文档具有数组特征?它不应该工作吗?

在 mongodb 我找到了

       db.rescuemodels.find({"features.properties":{"title":"Wild Wolfs"}})

所以它应该研究集合特征并给出所有对象的结果,properties.title 是野狼?

我的json

{
  "_id" : ObjectId("54f50753a879d4e045b24878"),
  "features" : [
     {
         "properties" : {
             "title" : "Alona 45D",
             "description" : "...",
             "date" : ISODate("2015-03-03T01:00:40.842Z"),
             "urgency" : "Low",
             "phone" : "675 675 345",
             "completion" : "NO",
             "rescuer" : "Aleksander Gagarin"
             },
         "geometry" : {
             "coordinates" : [
                 11.2637333,
                 23.1135565
                 ],
             "type" : "Point"
           },
        "type" : "Feature"
        },...etc

      ],
  "type" : "FeatureCollection",
    "__v" : 0
   }

好的,我成功地在文档的数组中找到了对象,所以现在只需替换​​剩下的一些属性。

 db.rescuemodels.find({"type":"FeatureCollection"},{"features": {$elemMatch:{"properties.title":"W"}}})

也许有人知道如何使这个声明正确

   db.rescuemodels.update({"type":"FeatureCollection"},{"features":{$elemMatch:{"properties.title":"W"}}},{$set:{"features":{"properties":{"title":"XXX"}}}})

您可能想使用 findOneByIdAndUpdate。在使用 mongodb 中的数组方面,要将项目添加到要使用 $push 的数组并从数组中删除项目,您要使用 $拉.

http://docs.mongodb.org/manual/reference/operator/update/push/