首页 > 解决方案 > 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}

标签: mongodbmongoose

解决方案


实验上(取决于您的集合的大小),您可以尝试使用带有参数的$unwind :includeArrayIndex

db.collection.aggregate([
    {
        $group: {
            _id: null,
            docs: { $push: "$$ROOT" }
        }
    },
    {
        $unwind: {
            path: "$docs",
            includeArrayIndex: "index"
        }
    },
    {
        $replaceRoot: {
            newRoot: {
                $mergeObjects: [ "$docs", { place: "$index" } ]
            }
        }
    }
])

蒙戈游乐场

您还可以考虑$out用上述聚合结果替换现有集合


推荐阅读