node.js - mongoDB 子文档匹配,其中 elemMatch 不是对象

标签 node.js mongoose

我有一个具有如下架构的子文档

{
    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/

相关文章:

javascript - 如何将参数属性分配给 self?

javascript - 在 Node.js 中,我找不到使用 URL 获取图像大小的 "require(' http')"依赖项

javascript - 直接 url 在 vuejs 中不起作用,但路由器推送有效

node.js - Mongodb 模式在几秒后清空

node.js - 将网页数据写入 TXT 文件

node.js - 如何更改 NodeJS 请求流响应

node.js - MongooseError [MongooseServerSelectionError] : connection <monitor> to 52. 206.125.240:27017 已关闭

javascript - 如何访问 MongoDB 中的图像文件并使用 Express.js 将它们发送到客户端

javascript - 如果 .find() mongoose 没有找到任何东西,请执行某些操作

node.js - Mongoose : using promises as parameters for other functions