问题描述
我是流星/mongo/js 作为堆栈的新手,我在 JSON 数组中迷失并引用它们.基于另一个SO答案(和文档),我想我很接近...
I'm new to meteor/mongo/js as a stack and I'm getting lost in JSON arrays and referencing them. Based another SO answer ( and the docs) I think I am close...
Orders 集合中的一个文档,该文档具有嵌套数组.
A document in the Orders collection, the document has nested arrays.
Order -> orderLines -> lineItems:
示例文档:
{
"_id" : "27tGpRtMWYqPpFkDN",
"orderLines" : [
{
"lineId" : 1,
"name" : "Cheese & Pickle",
"instructions" : "",
"lineItems" : [
{
"name" : "Cheddar Cheese",
"quantity" : 1
},
{
"name" : "Branston Pickle",
"quantity" : 1
},
{
"name" : "Focaccia Roll",
"quantity" : 1
}
]
}
]
}
我试图从流星/mongo shell 做的事情:
What I'm trying to do from the meteor/mongo shell:
- 将foo"的指令"添加到 lineId = 1 的 orderLines
- 在 lineItems 数组上放置一个新项目
这似乎挂了...
meteor:PRIMARY> db.orders.update({_id:"27tGpRtMWYqPpFkDN","orderLines.lineId":"1", {$set: {"orderLines.$.instructions":"foo"}})
...
这不喜欢查询中的标识符
This doesn't like the identifier in the query
meteor:PRIMARY> db.orders.update({_id:"27tGpRtMWYqPpFkDN", "orderLines.lineId":"1"}, {$push:{"orderLines.$.lineItems":" { "name" : "butter", "quantity" : 1}"}});
2015-10-27T16:09:54.489+0100 SyntaxError: Unexpected identifier
推荐答案
感谢大家的意见...不过我找到了一些答案,贴出来供参考
Thanks all for your comments... but I found out some answers, posted for reference
项目 1 - 对数组中的值使用 $set
由于两个拼写错误而失败,一个在查询结束时缺少结束 },第二个是在查询中引用 itemId 的值1".
This was failing due to two typos, one missing closing } at the end of the query, second was quoting the value "1" for itemId in the query.
这有效:
db.orders.update({_id:"27tGpRtMWYqPpFkDN", orderLines.lineId":1},
{$set: {"orderLines.$.instructions":"foo"}})
我还意识到,当我说它似乎挂起"时,是 cli 正在等待有效语句,因此提示缺少 } 或 )!
I also realised that when I said "It appears to hang" it is the cli waiting for a valid statement, so hints at a missing } or )!
项目 2 - 使用 $push 将数据添加到数组 - 2 层嵌套
由于引用数组数据而失败
This was failing due to quoting around the array data
db.orders.update({_id:"27tGpRtMWYqPpFkDN", "orderLines.lineId":1 },
{$push:{"orderLines.$.lineItems": { "name" : "butter", "quantity" : 1} }})
嵌套数组:可以使用 $ 位置运算符
我接下来要做的是在二级数组中的一个项目上使用 $set,这需要使用 $ 位置运算符两次:
What I want to do next is use $set on an item in the second level array, and this would require using the $ positional operator twice:
db.orders.update({"orderLines.lineId":1, lineItems.name:"Cheddar Cheese"},
{$set: {"orderLines.$.lineItems.$.quantity": 2}})
这会引发错误:
Too many positional (i.e. '$') elements found in path
有一个开放的 MongoDB 增强请求,但它自 2010 年以来一直开放
There is an open MongoDB enhancement request for this but it's been open since 2010
这篇关于Meteor/Mongo 嵌套数组更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!