You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1.6 KiB

title date draft toc images tags categories
Mongodb备忘录 2019-09-23T10:18:30+08:00 false true <nil> [database] server
  • 创建唯一索引

    // 删除重复key
    db.games2.aggregate([
        {
            "$group": {
                "_id": "$game_id",
                "dups": {
                    "$push": "$_id"
                },
                "count": {
                    "$sum": 1
                }
            }
        },
        {
            "$match": {
                "count": {
                    "$gt": 1
                }
            }
        }
    ]).forEach(function(doc) {
        doc.dups.shift();
        db.games2.remove({
            "_id": {
                "$in": doc.dups
            }
        });
    });
    
    // 创建索引
    db.games2.createIndex({"game_id": 1}, {unique: true});
    
  • 查找具有相同字段值的文档

    db.games2.find({$where: "this.fileId == this.fileUid"});
    
  • 创建管理员用户

    use admin
    db.createUser({
        user: "username",
        pwd: "password",
        roles: ["root"]
    })
    
    db.createUser({
        user: "myUserAdmin",
        pwd: passwordPrompt(), // or cleartext password
        roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
      }
    )
    
  • 创建数据库用户

    use mydb
    db.createUser({
        user: "myTester",
        pwd:  passwordPrompt(),   // or cleartext password
        roles: [ { role: "readWrite", db: "mydb" },
                 { role: "read", db: "reporting" } ]
      }
    )
    
  • 连接数据库

    mongo --port 27017 -u "myTester" --authenticationDatabase "mydb" -p