我需要更新MongoDB中的子数组子。
我的文件:
{
"_id" : ObjectId("5433d63cfafed42c083e0809"),
"name" : "Flavio",
"desc" : "feature",
"US" : [
{
"_id" : ObjectId("543ebeb473bc8d243d6b28dc"),
"name" : "asdf",
"desc" : "asdf",
"tasks" : [
{
"_id" : ObjectId("544029257266e4841735cde8"),
"name" : "hello",
"date" : "16/10/2014 05:23:01 pm",
"author" : "5424ac37eb0ea85d4c921f8b"
},
{
"_id" : ObjectId("54410bf33561315021a29e2b"),
"name" : "lol",
"date" : "17/10/2014 09:30:43 am",
"author" : "5424ac37eb0ea85d4c921f8b"
}
]
}
]
}
我需要将一个新数组推送到US.tasks._id = ObjectId(" 54410bf33561315021a29e2b")的任务。
任务更新预期:
{
"_id" : ObjectId("54410bf33561315021a29e2b"),
"name" : "lol",
"date" : "17/10/2014 09:30:43 am",
"author" : "5424ac37eb0ea85d4c921f8b"
"points" : [
{
"count" : 10,
"name": "pt"
}
]
}
我试着用:
db.projects.update({
"US.tasks": {
$elemMatch: {"_id": ObjectId("544029257266e4841735cde8")}
}
}, {
$push: {"US.$.tasks": {"points" : []}}
})
db.projects.update({
"US.tasks": {
$elemMatch: {"_id": ObjectId("544029257266e4841735cde8")}
}
}, {
$push: {"US.$.tasks.points": {"count" : 10, "name" : "pt"}}
})
但是新对象没有输入任务对象。
我如何解决这个问题并得到我期望的对象?
谢谢!
答案 0 :(得分:0)
还有另一种方法可以做到这一点
db.projects.find(
{
"US.tasks": {$elemMatch: {"_id": ObjectId("544029257266e4841735cde8")}}
}).forEach(function(item)
{
var us = item.US;
for (var i = 0; i < item.US.length; i++)
{
var tasks = item.US[i].tasks;
for (var i2 = 0; i2 < tasks.length; i2++)
{
var task = tasks[i2];
var id = task._id;
if(id == "544029257266e4841735cde8")
{
// add new filed
task.pointse = {};
break;
}
}
}
db.projects.save(item);
});