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"});