我有一个具有如下架构的子文档
{
things: [ { thing: { type: String }, otherThing: { type: String } ]
}
让我们假设它是这样填充的
[
{ thing: 'Thing 1', otherThing: '123-001'},
{ thing: 'Thing 2', otherThing: '123-002'},
{ thing: 'Thing 3', otherThing: '123-003'},
{ thing: 'Thing 4', otherThing: '123-004'}
]
我现在想插入到这个 Thing 5 中,但我想先检查它是否存在,所以我这样做:
Things.findOneAndUpdate(
{
things: {
$elemMatch: {
thing: {
$ne: 'Thing 5'
}
}
}
},
{
$push: {
things : {
thing: 'Thing 5',
otherThing: '123-005'
}
}
})
当我第一次运行脚本时,会插入 Thing 5。当我第二次运行它时,我预计它会失败,但它插入了重复的“Thing 5”。
我怀疑这是因为 $elemMatch 事物 $ne 与事物 1 - 4 匹配,因此会推送。我需要做什么才能让它基本上说“如果 Thing 5 不在这些子文档中”?
最佳答案
正如@Veeram 指出的那样,使用点表示法即可。
这段代码适用于我的 mongo:
db.col.update({ "things.thing":{$ne:"Thing 5"} }, {$push:{things:{'thing': 'Thing 5', 'otherThing': '123-005'}}})
点符号的有用链接:
https://docs.mongodb.com/manual/core/document/#dot-notation
希望对你有帮助
关于node.js - mongoDB 子文档匹配,其中 elemMatch 不是对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43469108/