[英]MongoDB findAndModify: >>> find and update object in document's array
[英]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是Wild Wolfs?
我的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的數組中並從數組中刪除項,需要使用$ pull。
http://docs.mongodb.org/manual/reference/operator/update/push/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.