MongoDB.为集合中的每个文档设置唯一编号 [英] MongoDB. Set unique number to each document in collection

查看:62
本文介绍了MongoDB.为集合中的每个文档设置唯一编号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对集合中的唯一值有一些疑问.有人知道我应该使用哪个运算符或条件来使用 updateMany 方法为 mongo 中的每个文档设置 uniq 编号吗?

I have some issue about unique values in collection. Does someone know which operator or condition should i use in order to set uniq number to each document in mongo with method updateMany?

例如:

{title: 'Hello'}, 
{title: 'World'},
{title: 'Mongo'},
{title: 'JSON'}

我需要在循环中附加 place 字段,值为 +1:

I need to append place field in loop with value +1:

{title: 'Hello', place: 1}, 
{title: 'World', place: 2},
{title: 'Mongo', place: 3},
{title: 'JSON', place: 4}

推荐答案

实验性(取决于您的收藏的大小)您可以尝试使用 $unwind 需要一个 includeArrayIndex参数:

Experimentally (depending on the size of your collection) you can try to use $unwind which takes an includeArrayIndex parameter:

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

蒙戈游乐场

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

You can also consider $out to replace existing collection with above aggregation result

这篇关于MongoDB.为集合中的每个文档设置唯一编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆