mongodb查询操作

数据

// 1
{
    "_id": ObjectId("5efb55e6975a0000b5002762"),
    "name": "剑士",
    "type": 1,
    "transfer": [
        {
            "name": "狂战士",
            "info": "使用血气攻击敌人"
        },
        {
            "name": "剑魂",
            "info": "擅长使用各种兵器进行作战"
        }
    ]
}

// 2
{
    "_id": ObjectId("5efb55e6975a0000b5002763"),
    "name": "格斗",
    "type": 2,
    "transfer": [
        {
            "name": "街霸",
            "info": "街头霸王,擅长街头格斗术"
        },
        {
            "name": "散打",
            "info": "擅长身体各部位灵活打击敌人"
        }
    ]
}

// 3
{
    "_id": ObjectId("5efb55e6975a0000b5002764"),
    "name": "枪手",
    "type": 3,
    "transfer": [
        {
            "name": "漫游",
            "info": "华丽的枪术与体术攻击"
        },
        {
            "name": "枪炮师",
            "info": "灵活驾驭使用重武器"
        }
    ]
}

// 4
{
    "_id": ObjectId("5efb585e975a0000b5002768"),
    "name": "枪手默",
    "type": 3,
    "transfer": [
        {
            "name": "漫游",
            "info": "华丽的枪术与体术攻击"
        },
        {
            "name": "枪炮师",
            "info": "灵活驾驭使用重武器"
        }
    ]
}

// 5
{
    "_id": ObjectId("5efb5b1b975a0000b500276a"),
    "name": "枪手默2",
    "sex": 1,
    "type": 3,
    "transfer": [
        {
            "name": "漫游",
            "info": "华丽的枪术与体术攻击"
        },
        {
            "name": "枪炮师",
            "info": "灵活驾驭使用重武器"
        }
    ]
}

// 6
{
    "_id": ObjectId("5efb5b25975a0000b500276b"),
    "name": "枪手默2",
    "sex": 1,
    "type": 3,
    "transfer": [
        {
            "name": "漫游",
            "info": "华丽的枪术与体术攻击"
        },
        {
            "name": "枪炮师",
            "info": "灵活驾驭使用重武器"
        }
    ]
}

例子

db.occupation.insert([
{"name":"枪手默2",sex:1, type:3,transfer:[{name:"漫游",info:"华丽的枪术与体术攻击"},{name:"枪炮师",info:"灵活驾驭使用重武器"}]}
])
 
 #查询所有 
 db.occupation.find({})
 
 #查询数量
 db.occupation.count({})
 
  #分页查询
 db.occupation.find({}).limit(1)
 
 
 #and操作
 db.occupation.find({type:{$gt:1},name:/手/})
 
 #or 操作
 db.occupation.find({$or:[{type:1},{type:2}]})
 
 #仅查询某些字段(前面是条件 后面{}是要查询的字段 带_id)
 db.occupation.find({sex:1},{name:1,type:1})
 
 #仅查询某些字段(前面是条件 后面{}是要查询的字段 不带_id)
 db.occupation.find({sex:1},{name:1,type:1,_id:0})
 
 #排除某些字段查询(前面是条件 后面{}排除要查询的字段 )
 db.occupation.find({sex:1},{name:0,type:0,_id:0})
 
 #查询嵌套字段 后面{} 值必须为相同的 都是1或者都是0 ,_id除外
 db.occupation.find({sex:1},{"transfer.name":1,name:1})
 
 
 #嵌套查询数组
 db.occupation.find({transfer:{$elemMatch:{name:/漫/}}})
 db.occupation.find({"transfer.name":"漫游" })
  
 #包含字段 或不包含
 db.occupation.find({sex:{$exists:false} })
 db.occupation.find({sex:{$exists:true} })
 db.occupation.find({sex:null })
 
 #筛选字段类型
 db.inventory.find( { sex : { $type: 10 } } )

你可能感兴趣的:(mongodb查询操作)