MongoDB $ pull语法 [英] MongoDB $pull syntax
问题描述
我在Mongodb中的$ pull有一个(希望)小的语法问题.
I'm having a (hopefully) small syntax problem with $pull in Mongodb.
bulk.find({_id: new mongo.ObjectID(req.session._id)}).updateOne({$pull: {
firstArray: {id: req.params.id},
'secondArray.firstArrayIds': req.params.id
'secondArray.$.firstArrayIds': req.params.id
}});
firstArray $pull
正常工作.
但是secondArray.firstArrayIds和/或secondArray.$.firstArrayIds没有.我在这里做错了什么?
The firstArray $pull
works just fine.
But the secondArray.firstArrayIds and/or secondArray.$.firstArrayIds does not. What am I doing wrong here?
这是我的数据结构:
clients: {
firstArray: [
{
_id: '153'.
someField1: 'someVal1',
}
...
]
secondArray: [
{
_id: '7423'.
someField1: 'someVal1',
firstArrayIds: [153, 154, 155, ...]
}
...
]
}
编辑,如果secondArray
中有多个嵌入对象,而firstArrayIds
可以包含我要删除的ID,该怎么办.换句话说,当删除firstdArray
中的对象时,我想删除 all 中所有secondArray
的引用,而不仅仅是第一个匹配项.
EDIT What if there are more than one embedded object in secondArray
which firstArrayIds
can contain the id i want to delete. In other words, when deleting an object in firstdArray
i want to delete references in all secondArray
's firstArrayIds
Not just the first match.
推荐答案
您的"secondArray"具有嵌套的元素结构,因此在更新中使用位置$
运算符时,必须标识要在查询中匹配的外部元素.您基本上需要这样的东西:
Your "secondArray" has a nested element structure, so you must identify the outer element you want to match in your query when using a positional $
operator in the update. You basically need something like this:
bulk.find({
"_id": new mongo.ObjectID(req.session._id),
"secondArray._id": "7423"
}).update({
"$pull": {
"firstArray": { "_id": "153" },
"secondArray.$.firstArrayIds": 153
}
});
因此,除了常规文档ID外,实际上还需要随请求一起传递两个" ID值.即使是嵌套的,也可以,因为您只在外部"级别匹配,并且仅在一个数组上匹配.如果您尝试匹配多个数组上的位置,那么位置运算符将无法做到这一点.
So there are in fact "two" id values you need to pass in with your request in addition to the general document id. Even though this is nested it is okay since you are only matching on the "outer" level and only on one array. If you tried to match the position on more than one array then this is not possible with the positional operator.
这篇关于MongoDB $ pull语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!