mongodb - MongoDB。为集合中的每个文档设置唯一编号
问题描述
我对收藏中的唯一值有一些疑问。有人知道我应该使用哪个运算符或条件来使用方法 updateMany 为 mongo 中的每个文档设置 uniq 编号吗?
例如:
{title: 'Hello'},
{title: 'World'},
{title: 'Mongo'},
{title: 'JSON'}
我需要place
在循环中附加值为+1的字段:
{title: 'Hello', place: 1},
{title: 'World', place: 2},
{title: 'Mongo', place: 3},
{title: 'JSON', place: 4}
解决方案
实验上(取决于您的集合的大小),您可以尝试使用带有参数的$unwind :includeArrayIndex
db.collection.aggregate([
{
$group: {
_id: null,
docs: { $push: "$$ROOT" }
}
},
{
$unwind: {
path: "$docs",
includeArrayIndex: "index"
}
},
{
$replaceRoot: {
newRoot: {
$mergeObjects: [ "$docs", { place: "$index" } ]
}
}
}
])
您还可以考虑$out用上述聚合结果替换现有集合
推荐阅读
- android - 谷歌地图片段显示,但没有地图
- c# - 将 nlog 添加到 .net core 3.0
- c# - 如何在 C# 中调用我的方法中的 onclick 按钮?
- django - Django 文件对象和 S3
- ios - 如何直播编码的 CMSampleBuffer 并在服务器端播放?
- c# - console.clear 在循环程序中的位置
- html - 在 Bootstrap 4 容器中定位元素居中和偏离中心
- javascript - 从单独的列表中分离和随机化项目
- ruby-on-rails - RuntimeError:无法加载默认凭据
- sql - SQL 代理 - 我可以删除中间作业步骤而不产生任何后果吗?