将数据插入到 mongodb 中的嵌套数组 [英] Inserting data to nested array in mongodb
问题描述
我有一个看起来像这样的文档
I have a document which looks like this
{
_id:1,
list_id:23,
name:'list01'
cards:[
{
id:3,
name:'card01'
categories:[{
id:10,
category:'section01',
tags:[{id:11,name:'tag01',is_selected: true}]
}]
}
]
}
我需要为给定的 list_id 在选定的 category 中插入/推送一些数据到 tags 数组,但出现错误说
I need to insert/push some data to tags array in a selected category for a given list_id but I'm getting an error saying
MongoError:在路径中找到太多位置(即$")元素'cards.$.categories.$.tags'
MongoError: Too many positional (i.e. '$') elements found in path 'cards.$.categories.$.tags'
这是我尝试过的查询.这个查询有什么问题?关于如何实现这一点的任何想法?
This is the query that I have tried out. What's wrong with this query any idea on how to achieve this?
db.collection(TABLE)
.updateOne(
{ list_id: 23, 'cards.categories.category': 'section01'},
{ $push: { 'cards.$.categories.$.tags': { name: 'tag02', id: uuidv4(), is_selected: true } } }
);
推荐答案
您不能使用多个 $ 位置,对于您的情况,您可以使用单个位置和 arrayFilters,
You can not use multiple $ positional, for your case you can use single positional and arrayFilters,
过滤位置运算符$[
标识匹配arrayFilters 条件的数组元素以进行更新操作,
The filtered positional operator $[<identifier>]
identifies the array elements that match the arrayFilters conditions for an update operation,
db.collection(TABLE).updateOne({
list_id: 23,
"cards.categories.category": "section01"
},
{
$push: {
"cards.$.categories.$[elem].tags": {
name: "tag02",
id: uuidv4(),
is_selected: true
}
}
},
{
arrayFilters: [
{ "elem.category": "section01" }
]
})
这篇关于将数据插入到 mongodb 中的嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!