获取包含数组中特定属性的 MongoDB 文档
为此,可以使用 $and 和点(.)符号。我们先创建一个带有文档的集合 -
>db.demo2.insertOne({"StudentInformation":[{"StudentName":"John","StudentAge":21},{"StudentName":"Mike","StudentAge":22}]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e08b56e25ddae1f53b62219")
}
>db.demo2.insertOne({"StudentInformation":[{"StudentName":"Carol","StudentAge":19},{"StudentName":"Bob","StudentAge":18}]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e08b58625ddae1f53b6221a")
}以下是使用 find() 方法显示集合中所有文档的查询 -
> db.demo2.find().pretty();
这将产生以下输出 -
{
"_id" : ObjectId("5e08b56e25ddae1f53b62219"),
"StudentInformation" : [
{
"StudentName" : "John",
"StudentAge" : 21
},
{
"StudentName" : "Mike",
"StudentAge" : 22
}
]
}
{
"_id" : ObjectId("5e08b58625ddae1f53b6221a"),
"StudentInformation" : [
{
"StudentName" : "Carol",
"StudentAge" : 19
},
{
"StudentName" : "Bob",
"StudentAge" : 18
}
]
}以下是获取包含数组中特定属性的文档的查询 -
>db.demo2.find({$and:[{"StudentInformation.StudentName":"Carol"},{"StudentInformation.StudentName":"Bob"}]});这将产生以下输出 -
{ "_id" : ObjectId("5e08b58625ddae1f53b6221a"), "StudentInformation" : [ { "StudentName" : "Carol", "StudentAge" : 19 }, { "StudentName" : "Bob", "StudentAge" : 18 } ] }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP