在我的Mongo聚合阶段,我有这样的文档:

{
  "_id": ObjectId('648031bd784fbf6081de41cf'),
  "orgId": 1,
  "applications": {
    "_id": ObjectId('6479ddda073ced427d04e9dd'),
    "orgId": 1,
    "firstTimeInstalled": [
      {
        "refId": ObjectId('648031bd784fbf6081de41cf'),
        "installDate": "2023-06-08T09:18:49.233+00:00"
      },
      {
        "refId": ObjectId('6479ddda073ced427d04e9dd'),
        "installDate": "2023-06-08T09:18:49.233+00:00"
      }
    ]
  }
}

我只想匹配其中Applations.firstTimeInstalled不包含其中refID等于文档根目录中的_id的对象的文档.

我试过这么做:

{
  $match: {
    "applications.firstTimeInstalled.refId": {
      $ne: "$_id"
    }
  }
}

但我仍然收到了不符合标准的文档,因此似乎不起作用.

更让我困惑的是,即使我这么做了:

{
  'applications.firstTimeInstalled.refId': {
    $nin: [ ObjectId('647746cfd9baa823f877c08f') ]
  }
}

如您所见,我手动注入了_id,但这仍然返回文档...那件事怎么可能?

推荐答案

a possible solution is to $map through the firstTimeInstalled array and if the mapped array has $anyElementTrue it means there is an element with _id === refId.
So take the negation with $not

db.collection.aggregate([
  {
    $match: {
      $expr: {
        $not: {
          $anyElementTrue: {
            $map: { 
              input: "$applications.firstTimeInstalled",
              in: { $eq: [ "$$this.refId", "$_id" ] }
            }
          }
        }
      }
    }
  }
])

playground

Mongodb相关问答推荐

使用查询参数过滤MongoDB Go驱动程序时出现问题

查找/查找单个深度嵌套文档的多个集合

如何根据两个 struct 创建一个Mongo文档?

在mongdob中按子文档筛选不起作用

MongoDB 对特定搜索查询的响应时间较长

如何获取键值对的对象,其中值仅具有 mongoDB 中的投影字段

MongoDB DB参考返回null值

Spring Boot 升级后未映射 Mongo 模板结果

如何在 mongodb golang 的单个更新调用中使用 $set 和 $inc?

PHP 无法加载动态库 (mongo.so)

当属性确实存在时,为什么mongoose模型的 hasOwnProperty 返回 false?

MongoDB 文档操作是原子的和隔离的,但它们是否一致?

MongoDB:单个数据库处理程序的 >5 个打开连接

Golang + MongoDB 嵌入类型(将一个 struct 嵌入到另一个 struct 中)

当前的 URL 字符串解析器已弃用

如何为 node.js 中的 MongoDB 索引指定 javascript 对象中的属性顺序?

Java + MongoDB:更新文档中的多个字段

无法连接到远程服务器上的 mongo

如何在mongoose的嵌套填充中 Select 特定字段

如何在 Ubuntu 10.04 中使用 --auth 选项重新启动 mongodb?