情景

Mongo DB文档示例 文档1 { _ID 123 客户:客户A 州:TX 城市:休斯顿 校验和:1111 IsBunled: }

Doc 2 { _id 1234 客户:客户B 州名:TX Registrant City:guangdong 校验和:1111 已绑定: }

文档3 { _ID 12345 客户:客户c 州:纽约州 城市:布法罗 校验和:2222 IsBunled:

}

在应用程序代码中使用州和城市字段填充校验和字段.

问题

如果校验和与1个以上的文档匹配,则将每个文档的IsBundled域填充为True.在我们的例子中,第一个和第二个文档需要使用isBundLED:True进行更新.我不是在应用程序代码中添加此逻辑,而是使用聚合管道寻找更好的解决方案

另外,如何通过Spring Boot Mongo AggregationUpdate类在应用程序代码中执行此聚合

推荐答案

版本高于MongoDB 4.4的版本可以使用$merge

end of aggregation pipeline处的AS $merge对于update the collection through aggregation.是必需的

For more information about $merge:https://www.mongodb.com/docs/manual/reference/operator/aggregation/merge/

$group: To group the matching documents.
$set: To modify the document
$gt: To check if greater than condition
$replaceRoot: To replace the current document structure by another.

MongoDB Playground link:https://mongoplayground.net/p/pV_UbQ-ADby

db.collection.aggregate([
  {
    $group: {
      _id: "$checksum",
      count: {
        $sum: 1
      },
      bundles: {
        $push: "$$ROOT"
      }
    }
  },
  {
    "$unwind": "$bundles"
  },
  {
    $set: {
      "bundles.IsBundled": {
        $gt: [
          "$count",
          1
        ]
      }
    }
  },
  {
    "$replaceRoot": {
      "newRoot": "$bundles"
    }
  }
])

Mongodb相关问答推荐

如何限制/筛选子文档中的条目?

在提供的文档(_Id)之后和之前,是否有一个Mongo操作来获取已排序(和/或过滤)集合中的文档计数?

MongoDB - 将数组元素转换为新字段

使用特定关键字和邻近度进行查询和过滤

spring-data-mongodb 上的 TopN 聚合

如何在 mongodb 中将一个方面的结果合并到一个有条件的列表中?

@DynamicPropertySource 未被调用(Kotlin、Spring Boot 和 TestContainers)

使用新字段插入数据或使用 updateOne mongodb 有条件地更新

mongoose中的 required是什么意思?

如何使用 mongoose 从 MongoDb 获取数据?

我怎样才能排序空值在 mongodb 中是最后排序的?

Mongo DB中的Upserting和Id问题

为什么 PyMongo 会抛出 AutoReconnect?

如何使用 java 驱动程序更新 mongo db 中的文档字段?

如何在 mongoDB 中聚合巨大的数组?

带有 Java 驱动程序的 MongoDB 聚合

没有参考选项的mongoose填充字段

如何使用 MongoDB C# 驱动程序有条件地组合过滤器?

MongoDB MapReduce - 发出一个键/一个值不调用reduce

mongodb安装失败运行mongod