mongodb - 为什么 MongoDb 在更新后按字母顺序对齐集合键

标签 mongodb php-mongodb

我已经看到,每当我们将任何值更新到 mongo 集合中时。更新后,它会按字母顺序重新排列按键。假设当前架构是

  _id:"Objectid(blah blah)"
     id: "1", 
fullname: "user",
 username: "username", 
password: "password",

更新后变成了

 _id:"Objectid(blah blah)"
    fullname:"user"
    id:"1"
    password:"password"
    username:"user"

我知道这没有问题。这不会影响任何事情,因为数组数据仍然与值相对应。但我只是想知道为什么会发生这种情况。

编辑:

这是mongoshell中的更新功能代码。但这对我没有帮助

function (query, obj, upsert, multi) {
    assert(query, "need a query");
    assert(obj, "need an object");
    var firstKey = null;
    for (var k in obj) {
        firstKey = k;
        break;
    }
    if (firstKey != null && firstKey[0] == "$") {
        this._validateObject(obj);
    } else {
        this._validateForStorage(obj);
    }
    if (typeof upsert === "object") {
        assert(multi === undefined, "Fourth argument must be empty when specifying upsert and multi with an object.");
        opts = upsert;
        multi = opts.multi;
        upsert = opts.upsert;
    }
    this._db._initExtraInfo();
    this._mongo.update(this._fullName, query, obj, upsert ? true : false, multi ? true : false);
    this._db._getExtraInfo("Updated");
}

最佳答案

文档说它们会在文档大小增加超过分配的大小时重新排序,但是,每当文档大小发生变化时,它们似乎都会重新排序(如果大小相同,则不会更改)。

例如,这里第一个命令不会改变,但第二个命令会改变。

> db.t3.insert({_id : 1234',id:'xxx',
fullname:'use1',password:'password','username':'user'})
> db.t3.update({'_id':'1234'},{$set : {fullname:'use1'}})
> db.t3.findOne()
{
    "_id" : "1234",
    "id" : "xxx",
    "fullname" : "use1",
    "password" : "password",
    "username" : "user"
}
> db.t3.update({'_id':'1234'},{$set : {fullname:'use11'}})
> db.t3.findOne()
{
    "_id" : "1234",
    "fullname" : "use11",
    "id" : "xxx",
    "password" : "password",
    "username" : "user"
}

看这里https://jira.mongodb.org/browse/SERVER-2592

关于mongodb - 为什么 MongoDb 在更新后按字母顺序对齐集合键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15454150/

相关文章:

mongodb - 为什么 indexOnly==false

linux - MongoDB 日志轮转配置

node.js - MongoDB Atlas 和 Node JS - 架构布局

mongodb - 如何在 mongodb 中进行条件更新?

mongodb - 如何在 Mongodb 中获取条件字段

php - MongoDB 和 PHP 库游标超时

node.js - 使用 mongoose 填充到 "join"匹配的子记录

java - Neo4J 与 APOC 和 MongoDB 驱动程序,限制从 Mongo 返回的记录

php mongoDB aggregate() 返回 MongoDB\Driver\Cursor 对象而不是结果

php - 读取/删除 Lithium 0.11 和 MongoDB 中的相关数据/实体