【问题标题】:Mongoose get documents where id does NOT exist inside nested objectMongoose 获取嵌套对象中不存在 id 的文档
【发布时间】:2022-02-05 09:29:52
【问题描述】:

我正在尝试查询对象数组中不存在用户 ID 的文档列表。

数据库(文档)如下所示:

[
  { 
    title: 'object 1',
    description: 'description 1',
    members: [
      { profile: { id: '123', ...}, data: {} },
      { profile: { id: 'abc', ...}, data: {} },
      { profile: { id: 'def', ...}, data: {} }, 
    ]
  },
  { 
    title: 'object 2',
    description: 'description 3',
    members: [
      { profile: { id: 'aaa', ...}, data: {} },
      { profile: { id: 'bbb', ...}, data: {} },
      { profile: { id: 'ccc', ...}, data: {} }, 
    ]
  },
]

鉴于我的用户 ID 是“aaa”,我正在尝试查询我不是会员的所有文档。

我可以使用此代码成功查询我的用户 ID 所在的所有文档:

await this._repository.findManyByQuery(
  {
    members: {
      $elemMatch: {
        "profile.id": "aaa",
      },
    },
  },
)

但是,我希望查询我的 ID 不存在的所有对象。我尝试过使用$ne,但它仍然返回用户 ID 存在的文档

members: {
  $elemMatch: {
    "profile.id": { $ne: "aaa" },
  },
},

我想我正在寻找 $elemMatch 的反面,但在数组中查询

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    您可以像这样使用$not 来否定$elemMatch

    await this._repository.findManyByQuery({
      members: {
        "$not": {
          $elemMatch: {
            "profile.id": "aaa"
          }
        }
      }
    })
    

    例如here

    【讨论】:

    • 干杯伙伴,我以前试过 $not 但它嵌套在 $elemMatch 中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-03
    • 2011-11-10
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    相关资源
    最近更新 更多