Mongodb备忘录

  • 创建唯一索引

    // 删除重复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