简体   繁体   English

增加mongo db中的索引

[英]Incrementing index in mongo db

When adding a field called date in mongo db, I can do just: 在mongo db中添加一个名为date的字段时,我可以这样做:

date: {
    type: Date,
    default: Date.now
}

and it will automatically add date field to my new collection when it was created. 它会在创建时自动将date字段添加到我的新集合中。 Is there some way to add a self-incrementing index ( id ) to my collections? 有没有办法在我的集合中添加自增量索引( id )?

Note : I tried to do it on client side, however with every time I push collection with ( id ) field, its being deleted from the collection and replaced with _id which is a long string with random characters. 注意 :我尝试在客户端执行此操作,但每次我使用( id )字段推送集合时,它将从集合中删除并替换为_id ,这是一个带有随机字符的长字符串。 Way to long! 好长的路!

Looking for every hints. 寻找每一个提示。

Edit: code responsible for adding use to db 编辑:负责向db添加使用的代码

app.post("/users", function (req, res) {
    createUser(req.body, function (err, user) {
        if (err) {
            return res.json(err);
        }
        return res.json(user);
    });
});

MongoDB automatically makes unique ids for each object in the database, resulting in each entry having a unique _id field being an ObjectId . MongoDB自动为数据库中的每个对象创建唯一ID,导致每个条目都有一个唯一的_id字段是ObjectId You don't really need to worry about specifying custom ids. 您实际上不必担心指定自定义ID。

You can sort by _id if you want objects roughly in the order they were created, or you could add a date field which is set on creation and sort by that. 如果您希望对象大致按照创建顺序排序,则可以按_id排序,或者可以添加在创建时设置的日期字段并按其排序。

Other than that, I'm not sure what you'd gain by having auto incrementing ids 除此之外,我不确定通过自动递增ID会获得什么

There are multiple ways to implement an auto-increment index but it is not considered a good practice. 有多种方法可以实现自动增量索引,但这不是一种好的做法。

Detailed information here: Auto increment in MongoDB to store sequence of Unique User ID 详细信息: MongoDB中的自动增量以存储唯一用户ID的序列

Check Rizwan Siddiquee answer about how to implement it with a stored javascript function. 检查Rizwan Siddiquee关于如何使用存储的javascript函数实现它的答案。

Another way would be to implement it on application layer using any kind of ODM but this is obviously dangerous and not so trustable for serious applications. 另一种方法是使用任何类型的ODM在应用层上实现它,但这显然是危险的,并且对于严肃的应用程序而言不那么可信。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM