{
"doc_id": 1234,
"pars": [
{
"par_id": 4567,
"someNode": "...",
"lines": [
{
"line_id": 8901,
"someOtherNode": "...",
"text": "Foo"
},
]
}
]
}
如何更新知道text
,doc_id
和par_id
的正确节点中的line_id
字段?
我无法使用此查询,因为我没有与par_id
和line_id
对应的节点索引
con.db.col.update(
{'_id': doc_id},
{'$set': { "pars.?.lines.?.text": "Bar" } }
)
答案 0 :(得分:0)
Because updating based on a match in nested arrays is not yet supported in MongoDB,您需要重新排列架构。现在你有一个段落数组,每个段落都是一个行数组。我建议将段落设为文档,其字段名为paragraphIds,而不是数组。您可以将这些行保存为数组,然后可以使用"$" positional operator通过paragraphId和lineId进行更新:
> db.collection.insertOne({
... "doc_id": 1234,
... "pars": {
... 4567: {
... "someNode": "...",
... "lines": [
... {
... "line_id": 8901,
... "someOtherNode": "...",
... "text": "Foo"
... },
... ]
... }
... }
... })
{
"acknowledged" : true,
"insertedId" : ObjectId("58ecb95e475838c0db6efd9d")
}
> db.collection.updateOne({
... "doc_id": 1234,
... "pars.4567.lines.line_id": 8901
... }, {
... "$set": {"pars.4567.lines.$.text": "Bar"}
... })
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
> db.collection.findOne({"doc_id": 1234})
{
"_id" : ObjectId("58ecb95e475838c0db6efd9d"),
"doc_id" : 1234,
"pars" : {
"4567" : {
"someNode" : "...",
"lines" : [
{
"line_id" : 8901,
"someOtherNode" : "...",
"text" : "Bar"
}
]
}
}
}
答案 1 :(得分:-1)
db.col.update(
{"_id": doc_id, "par_id": 4567, "pars.lines.line_id":8901},
{$set: { "pars.$.lines.$.text":"ANY_TEXT_YOU_WANT" } },
function(){} //callback function)
答案 2 :(得分:-1)
$$是特殊运算符(新位置运算符)
你可以做这样的事情 -db.col.update(
{"_id": doc_id, "par_id": 4567, "pars.lines.line_id":8901},
{$set: { "pars.lines.$$.text":"ANY_TEXT_YOU_WANT" } },
function(){} //callback function)