欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 金融 > MongoDB - 集合方法 db.collection.find()

MongoDB - 集合方法 db.collection.find()

2024/10/24 11:19:50 来源:https://blog.csdn.net/qq_42764468/article/details/140757224  浏览:    关键词:MongoDB - 集合方法 db.collection.find()

文章目录

      • 1. query 参数
      • 2. projection 参数
        • 2.1 仅返回指定的字段
        • 2.2 排除字段
        • 2.3 显式排除_id字段
      • 3. 修改游标行为
        • 3.1 为结果集中的文档排序
        • 3.2 限制要返回的文档数量
        • 3.3 控制结果集的起点
        • 3.4 组合游标方法

db.collection.find( <query>, <projection>, <options> )
ParameterTypeDescription
querydocument可选。使用查询运算符指定选择筛选器。
projectiondocument可选。指定与查询过滤器匹配的文档中要返回的字段。
optionsdocument可选。指定查询的附加选项。

projection 参数确定匹配文档中返回哪些字段。projection 参数采用以下形式的文档:

{ <field1>: <value>, <field2>: <value> ... }

构造测试数据:

db.inventory.insertMany( [{ _id: 1, item: { name: "ab", code: "123" }, qty: 15, tags: [ "A", "B", "C" ] },{ _id: 2, item: { name: "cd", code: "123" }, qty: 20, tags: [ "B" ] },{ _id: 3, item: { name: "ij", code: "456" }, qty: 25, tags: [ "A", "B" ] },{ _id: 4, item: { name: "xy", code: "456" }, qty: 30, tags: [ "B", "A" ] },{ _id: 5, item: { name: "mn", code: "000" }, qty: 20, tags: [ [ "A", "B" ], "C" ] }
] )

1. query 参数

db.inventory.find({})
db.inventory.find( { _id: 5 } )
db.inventory.find( { "item.name": "ab" } )
db.inventory.find({ _id: { $in: [ 1, 2 ] } }
)

2. projection 参数

2.1 仅返回指定的字段
db.inventory.find( { qty: 20 },{ "item.name": 1, tags: 1 }
)
// 1
{"_id": 2,"item": {"name": "cd"},"tags": ["B"]
}// 2
{"_id": 5,"item": {"name": "mn"},"tags": [["A","B"],"C"]
}
2.2 排除字段

除非在投影文档 _id: 0 中显式排除 _id 字段,否则将返回 _id 字段。

db.inventory.find({ qty: 20 },{ "item.name": 0, tags: 0 }
)
// 1
{"_id": 2,"item": {"code": "123"},"qty": 20
}// 2
{"_id": 5,"item": {"code": "000"},"qty": 20
}
2.3 显式排除_id字段
db.inventory.find( { qty: 20 },{ "item.name": 1, tags: 1 ,_id: 0}
)
// 1
{"item": {"name": "cd"},"tags": ["B"]
}// 2
{"item": {"name": "mn"},"tags": [["A","B"],"C"]
}

3. 修改游标行为

3.1 为结果集中的文档排序

sort() 方法对结果集中的文档排序。

db.inventory.find({},{ _id: 0, tags: 0, item: 0}
).sort( { qty: 1 } )
// 1
{"qty": 15
}// 2
{"qty": 20
}// 3
{"qty": 20
}// 4
{"qty": 25
}// 5
{"qty": 30
}
3.2 限制要返回的文档数量

limit() 方法限制结果集中的文档数量。

db.inventory.find().limit(2)
// 1
{"_id": 1,"item": {"name": "ab","code": "123"},"qty": 15,"tags": ["A","B","C"]
}// 2
{"_id": 2,"item": {"name": "cd","code": "123"},"qty": 20,"tags": ["B"]
}
3.3 控制结果集的起点

skip() 方法控制结果集的起点。

db.inventory.find().skip( 3 )
// 1
{"_id": 4,"item": {"name": "xy","code": "456"},"qty": 30,"tags": ["B","A"]
}// 2
{"_id": 5,"item": {"name": "mn","code": "000"},"qty": 20,"tags": [["A", "B"],"C"]
}
3.4 组合游标方法
db.inventory.find().sort( { qty: 1 } ).limit( 2 )
db.bios.find().limit( 2 ).sort( { qty: 1 } )

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com