将JSON推送到现有数组的语法有什么问题?
> db.accounts.update({"accounts.username":"gattra"},{$push:{logbooks:[{firstLogbook:{"date":"Aug 24, 2015","location":"Brunswick,ME"}}]}})
WriteResult({ "nMatched" : 0, "nUpserted" : 0, "nModified" : 0 })
另一次尝试:
> db.accounts.update(
{"accountInfo.username":"gattra"},
{ $addToSet: { 'logbooks.$.firstLogbook': toInsert } }
)
WriteResult({
"nMatched" : 0,
"nUpserted" : 0,
"nModified" : 0,
"writeError" : {
"code" : 16837,
"errmsg" : "The positional operator did not find the match needed from the query. Unexpanded update: logbooks.$.firstLogbook"
}
})
它看起来似乎没有找到符合我条件的匹配项,但是如果您查看下面的文档,就可以看到有一个帐户,其中包含用户名" gattra&# 34。
我是MongoDB的新手,我不太了解网站文档。
包含数组的文档:
> db.accounts.find().pretty()
{
"_id" : ObjectId("55d6450dd745a23c6cfa2b23"),
"accountInfo" : {
"username" : "gattra",
"password" : "PASS",
"userid" : 1111
},
"logbooks" : [
{
"firstLogbook" : [
{
"date" : "August 10, 2015",
"location" : "Portland, ME",
"routeName" : "Trendsetter",
"grade" : "V10",
"type" : "Bouldering",
"time" : "4:30.05",
"pcl" : 10,
"notes" : "My first V10 ever!",
"photoUrl" : ""
}
]
}
]
}
编辑:正确版本 感谢@Allen Chou的帮助。
我最终重建了帐户集合,如下所示:
{
"accountInfo":{
"username":"broderick",
"password":"PASS",
"userid":1111
},
"logbooks":
[{
"firstLogbook": {
"id":1234,
"info":[{
"date":"August 10, 2015",
"location":"Portland, ME",
"routeName":"Trendsetter",
"grade":"V10",
"type":"Bouldering",
"time": "4:30.05",
"pcl":10,
"notes":"My first V10 ever!",
"photoUrl":""
}]
}
}]
}
通过添加"id"
字段,我可以将id用作指定参数。然后我将内容放在"info"
字段中。
工作查询:
> db.accounts.update({"accountInfo.username": "broderick", "logbooks.firstLogbook.id":1234},{$push:{"logbooks.$.firstLogbook.info":{"date":"Aug 24, 2015"}}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
答案 0 :(得分:1)
您希望将新文档添加到firstLogbook数组中。
对于Array update中的 $ ,它标识要更新的数组中的元素,而不显式指定数组中元素的位置,
基本语法是:
db.collection.update(
{ <array>: value ... }, // locate array to update
{ <update operator>: { "<array>.$" : value } }
)
因此,根据上述格式,这可能会解决您的问题。
db.accounts.update(
{
"accountInfo.username": "gattra",
"logbooks.firstLogbook": { $exists: true }
},
{
$push:
{
"logbooks.$.firstLogbook" :
{
"date":"Aug 24, 2015", "location":"Brunswick,ME"
}
}
}
)