MongoDB find() 方法2025年3月17日 | 阅读 3 分钟 引言在 mongoDB 中,find() 方法用于从表中获取特定数据。换句话说,它用于选择表中的数据。它也用于返回所选数据的所有事件。 find() 方法由两个参数组成,通过这两个参数我们可以找到特定的记录。 语法
![]() 示例在下面的示例中,我们将使用 {
"_id" : ObjectId("56254d4fdf2222265r4g12ds3d65f"),
"name" : "Mick",
"Course" : "btech",
"batch_year" : 2018,
"language" : ["c++", "java", "python"],
}
{
"_id" : ObjectId("56254d4fdf2222265r4g12ds3d691"),
"name" : "Zoya",
"Course" : "BCA",
"batch_year" : 2020,
"language" : ["C#", "JavaScript"],
}
{
"_id" : ObjectId("56254d4fdf2222265r4g12ds3d655"),
"name" : "Jonny",
"Course" : "MCA",
"batch_year" : 2019,
"language" : ["C#", "java", "PHP"],
}
{
"_id" : ObjectId("56254d4fdf2222265r4g12ds3d678"),
"name" : "Oliver",
"Course" : "BA",
"batch_year" : 2017,
"language" : ["c", "PHP"],
}
{
"_id" : ObjectId("56254d4fdf2222265r4g12ds3d665"),
"name" : "Mia",
"Course" : "btech",
"batch_year" : 2020,
"language" : ["HTML", "CSS", "PHP"],
}
示例 1:查找 student 集合中的所有文档。当我们需要所有记录时,我们不在查询中使用任何参数。 输出 ![]() 示例 2:查找特定文档在此示例中,我们仅检索学生课程为 btech 的学生的文档。 输出 >db.student.find({Course : btech})
{
"_id" : ObjectId("56254d4fdf2222265r4g12ds3d65f"),
"name" : "Mick",
"Course" : "btech",
"batch_year" : 2018,
"language" : ["c++", "java", "python"],
}
{
"_id" : ObjectId("56254d4fdf2222265r4g12ds3d665"),
"name" : "Mia",
"Course" : "btech",
"batch_year" : 2020,
"language" : ["HTML", "CSS", "PHP"],
}
示例 3:查找嵌入式文档在此示例中,我们仅检索与给定数组中的值匹配的学生的文档。 输出 >db.student.find({score:{HTML, CSS, PHP}})
{
"_id" : ObjectId("56254d4fdf2222265r4g12ds3d665"),
"name" : "Mia",
"Course" : "btech",
"batch_year" : 2020,
"language" : ["HTML", "CSS", "PHP"],
}
示例 4:使用指定字段显示文档在此示例中,我们借助投影仅检索学生姓名字段。 输出 >db.student.find({},{name:1, _id:0})
{ "name" : "Mick" }
{ "name" : "Zoya" }
{ "name" : "Jonny" }
{ "name" : "Oliver" }
{ "name" : "Mia" }
示例 5:使用 limit() 方法仅显示两个文档输出 >db.student.find().limit(3)
{
"_id" : ObjectId("56254d4fdf2222265r4g12ds3d65f"),
"name" : "Mick",
"Course" : "btech",
"batch_year" : 2018,
"language" : ["c++", "java", "python"],
}
{
"_id" : ObjectId("56254d4fdf2222265r4g12ds3d691"),
"name" : "Zoya",
"Course" : "BCA",
"batch_year" : 2020,
"language" : ["C#", "JavaScript"],
}
{
"_id" : ObjectId("56254d4fdf2222265r4g12ds3d655"),
"name" : "Jonny",
"Course" : "MCA",
"batch_year" : 2019,
"language" : ["C#", "java", "PHP"],
}
示例 6:使用条件标准查找特定文档在此示例中,我们仅检索 batch_year 大于 2018 的学生的文档。 输出 >db.student.find({batch_year : {$gt : 2018}})
{
"_id" : ObjectId("56254d4fdf2222265r4g12ds3d691"),
"name" : "Zoya",
"Course" : "BCA",
"batch_year" : 2020,
"language" : ["C#", "JavaScript"],
}
{
"_id" : ObjectId("56254d4fdf2222265r4g12ds3d655"),
"name" : "Jonny",
"Course" : "MCA",
"batch_year" : 2019,
"language" : ["C#", "java", "PHP"],
}
{
"_id" : ObjectId("56254d4fdf2222265r4g12ds3d665"),
"name" : "Mia",
"Course" : "btech",
"batch_year" : 2020,
"language" : ["HTML", "CSS", "PHP"],
}
|
我们请求您订阅我们的新闻通讯以获取最新更新。