我有一份MongoDB文件:
{
"_id" : ObjectId("553e0c2ec9ad2dbe13cc17cc"),
"country" : "ireland",
"games" : [
{
"title" : "Test",
"draws" : [ ]
},
{
"title" : "Test 2",
"draws" : [ ]
},
{
"title" : "Test 3",
"draws" : [ ]
}
]
}
我想在绘制键下存储多个具有相同结构的对象。现在,如果我想返回测试游戏,我会执行以下Mongo查询:
db.data.find({country:"ireland"},{games:{$elemMatch:{title:"Test"}}})
...返回:
{
"_id" : ObjectId("553e0c2ec9ad2dbe13cc17cc"),
"games" : [
{
"title" : "Test",
"draws" : [ ]
}
]
}
如何在提取键中输入数据?这是我想要实现的一个例子:
{
"_id" : ObjectId("553e0c2ec9ad2dbe13cc17cc"),
"country" : "ireland",
"games" : [
{
"title" : "Test",
"draws" : [{
"date":"20150207",
"numbers":[10,20,30,40,50,60]
},
{
"date":"20150214",
"numbers":[09,07,22,31,39,30]
},
{
"date":"20150221",
"numbers":[11,07,22,13,30,01]
}]
},
{
"title" : "Test 2",
draws : [{
"date":"20150207",
"numbers":[03,08,21,19,24,01]
},
{
"date":"20150214",
"numbers":[19,17,02,11,19,32]
},
{
"date":"20150221",
"numbers":[31,27,12,10,15,11]
}]
},
{
"title" : "Test 3",
draws : [{
"date":"20150207",
"numbers":[10,17,29,33,31,11]
},
{
"date":"20150214",
"numbers":[12,17,19,33,31,02]
},
{
"date":"20150221",
"numbers":[01,17,32,23,31,01]
}]
}
]
}
我尝试使用 upsert 更新()但每次都在编写新文档。
答案 0 :(得分:0)
我使用以下代码插入子文档。
db.data.update({country:"ireland",games:{$elemMatch:{title:"Test"}}},
{
$push: {
'games.$.draws': [
{"date":"20150207",
"numbers":[10,20,30,40,50,60]}
]}
})
结果如下。
{
"_id" : ObjectId("553e2a32f077cac2cbb9a033"),
"country" : "ireland",
"games" : [
{
"title" : "Test",
"draws" : [
[
{
"date" : "20150207",
"numbers" : [
10,
20,
30,
40,
50,
60
]
}
]
]
},
{
"title" : "Test 2",
"draws" : []
},
{
"title" : "Test 3",
"draws" : []
}
]
}