示例
查询所有记录,不指定 cond 和 sel 字段。
db.sample.employee.find()
查询匹配条件的记录,即设置 cond 参数的内容。如下操作返回集合 employee 中符合 条件 age 字段值大于25且 name 字段值为"Tom"的记录。
db.sample.employee.find( { age: { $gt: 25 }, name: "Tom" } )
指定返回的字段名,即设置 sel 参数的内容。如有记录{ age: 25, type: "system" } 和{ age: 20, name: "Tom", type: "normal" },如下操作返回记录的age字段和name字段。
db.sample.employee.find( null, { age: "", name: "" } )
{
"age": 25,
"name": ""
}
{
"age": 20,
"name": "Tom"
}
使用索引 ageIndex 遍历集合 employee 下存在 age 字段的记录,并返回。
db.sample.test.find( {age: {$exists:1} } ).hint( { "": "ageIndex" } )
{
"_id": {
"$oid": "5812feb6c842af52b6000007"
},
"age": 10
}
{
"_id": {
"$oid": "5812feb6c842af52b6000008"
},
"age": 20
}
选择集合 employee 下 age 字段值大于10的记录(如使用 $gt 查询),从第5条记录开始返回,即跳过前面的四条记录。
db.sample.employee.find( { age: { $gt: 10 } } ).skip(3).limit(5)
如果结果集的记录数不大于3,那么无记录返回; 如果结果集的记录数大于3,则从第4条开始, 最多返回5条记录。
返回集合 employee 中 age 字段值大于20的记录(如使用 $gt 查询),设置只返回记录的 name 和 age 字段,并按 age 字段值的升序排序。
db.sample.employee.find( { age: { $gt: 20 } }, { age: "", name: "" } ).sort( { age: 1 } )
点击巨杉数据库文档中心了解更多信息