如何在MongoDB中搜索对象数组?
要在MongoDB中搜索对象数组,可以使用$elemMatch运算符。此运算符使我们可以从数组对象中搜索多个组件。
为了理解上述概念,让我们用文档创建一个集合。使用文档创建集合的查询如下-
> db.searchArrayDemo.insertOne({"EmployeeFirstName":"Adam","EmployeeLastName":"Smith","EmployeeDateOfBirth":new ISODate("1992-01-31 13:45:10"),... "EmployeeSkills":["Spring and Hibernate Framework","Machine Learning"],
... "EmployeeDetails":[
... {
... "EmployeePerformanceArea":"Java",
... "Year":2001
... },
... {
... "EmployeePerformanceArea":"Python",
... "Year":2005
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5c77b3812386c62d05142a6a")
}
> db.searchArrayDemo.insertOne({"EmployeeFirstName":"Carol","EmployeeLastName":"Taylor",
"EmployeeDateOfBirth":new ISODate("1993-04-21 11:10:20"),
"EmployeeSkills":["C++","Cloud Computing"], "EmployeeDetails":[ {
"EmployeePerformanceArea":"C++", "Year":1998 }, { "EmployeePerformanceArea":"C++
Game Developer", "Year":2007 } ] } );
{
"acknowledged" : true,
"insertedId" : ObjectId("5c77b58f2386c62d05142a6b")
}
在find()
method的帮助下显示集合中的所有文档。查询如下-
> db.searchArrayDemo.find().pretty();
以下是输出-
{"_id" : ObjectId("5c77b3812386c62d05142a6a"),
"EmployeeFirstName" : "Adam",
"EmployeeLastName" : "Smith",
"EmployeeDateOfBirth" : ISODate("1992-01-31T13:45:10Z"),
"EmployeeSkills" : [
"Spring and Hibernate Framework",
"Machine Learning"
],
"EmployeeDetails" : [
{
"EmployeePerformanceArea" : "Java",
"Year" : 2001
},
{
"EmployeePerformanceArea" : "Python",
"Year" : 2005
}
]
}
{
"_id" : ObjectId("5c77b58f2386c62d05142a6b"),
"EmployeeFirstName" : "Carol",
"EmployeeLastName" : "Taylor",
"EmployeeDateOfBirth" : ISODate("1993-04-21T11:10:20Z"),
"EmployeeSkills" : [
"C++",
"Cloud Computing"
],
"EmployeeDetails" : [
{
"EmployeePerformanceArea" : "C++",
"Year" : 1998
},
{
"EmployeePerformanceArea" : "C++ Game Developer",
"Year" : 2007
}
]
}
这是在MongoDB中搜索对象数组的查询。
情况1
找到给定元素时。
查询如下-
> db.searchArrayDemo.find({EmployeeDetails:{$elemMatch:{EmployeePerformanceArea : "C++", Year : 1998}}}).pretty();
以下是输出-
{"_id" : ObjectId("5c77b58f2386c62d05142a6b"),
"EmployeeFirstName" : "Carol",
"EmployeeLastName" : "Taylor",
"EmployeeDateOfBirth" : ISODate("1993-04-21T11:10:20Z"),
"EmployeeSkills" : [
"C++",
"Cloud Computing"
],
"EmployeeDetails" : [
{
"EmployeePerformanceArea" : "C++",
"Year" : 1998
},
{
"EmployeePerformanceArea" : "C++ Game Developer",
"Year" : 2007
}
]
}
情况二
未找到给定元素时。
查询如下-
> db.searchArrayDemo.find({EmployeeDetails:{$elemMatch:{EmployeePerformanceArea : "C", Year : 1996}}}).pretty();
在这里,当找不到给定的元素时,您什么也不会得到
以上是 如何在MongoDB中搜索对象数组? 的全部内容, 来源链接: utcz.com/z/321703.html