如何使用MongoDB匹配数组中的多个条件?
要匹配数组中的多个条件,请使用aggregate()
。让我们创建一个包含文档的集合-
> db.demo84.insertOne({... "EmployeeDetails": [
... {Name: 'John', Salary:45000, isMarried: true},
... {Name: 'Chris', Salary:50000, isMarried: false}
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e2c0a3471bf0181ecc422a5")
}
> db.demo84.insertOne({
... "EmployeeDetails": [
... {Name: 'Sam', Salary:56000, isMarried: false},
... {Name: 'Bob', Salary:50000, isMarried: false}
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e2c0a4071bf0181ecc422a6")
}
在find()
方法的帮助下显示集合中的所有文档-
> db.demo84.find();
这将产生以下输出-
{"_id" : ObjectId("5e2c0a3471bf0181ecc422a5"), "EmployeeDetails" : [
{ "Name" : "John", "Salary" : 45000, "isMarried" : true },
{ "Name" : "Chris", "Salary" : 50000, "isMarried" : false }
]
}
{
"_id" : ObjectId("5e2c0a4071bf0181ecc422a6"), "EmployeeDetails" : [
{ "Name" : "Sam", "Salary" : 56000, "isMarried" : false },
{ "Name" : "Bob", "Salary" : 50000, "isMarried" : false }
]
}
以下是匹配数组中多个条件的查询-
示例
> db.demo84.aggregate(... { "$match": {
... "EmployeeDetails": {
... "$elemMatch": {
... "Name": "Chris",
... "isMarried": false
... }
... }
... }}
... );
这将产生以下输出-
{"_id" : ObjectId("5e2c0a3471bf0181ecc422a5"), "EmployeeDetails" : [
{ "Name" : "John", "Salary" : 45000, "isMarried" : true },
{ "Name" : "Chris", "Salary" : 50000, "isMarried" : false }
]
}
以上是 如何使用MongoDB匹配数组中的多个条件? 的全部内容, 来源链接: utcz.com/z/316790.html