MongoDB 查询在对象数组中查找多次匹配的内容?
为此,使用 $ 和 $regex。 $ 对一系列一个或多个表达式执行逻辑 AND 操作,并选择满足该数组中所有表达式的文档。
让我们创建一个包含文档的集合 −
> db.demo525.insertOne({"details":[{Name:"Chris","CountryName":"US"}]});{ "acknowledged" : true, "insertedId" : ObjectId("5e8ae5ef437efc8605595b66") } > db.demo525.insertOne({"details":[{Name:"Bob","CountryName":"UK"}]});{ "acknowledged" : true, "insertedId" : ObjectId("5e8ae5f8437efc8605595b67") } > db.demo525.insertOne({"details":[{Name:"chris","CountryName":"us"}]});{ "acknowledged" : true, "insertedId" : ObjectId("5e8ae602437efc8605595b68") } > db.demo525.insertOne({"details":[{Name:"Mike","CountryName":"UK"}]});{ "acknowledged" : true, "insertedId" : ObjectId("5e8ae60b437efc8605595b69") }
借助 find() 方法在集合中显示所有文档 −
> db.demo525.find();
这将产生以下输出 −
{ "_id" : ObjectId("5e8ae5ef437efc8605595b66"), "details" : [ { "Name" : "Chris", "CountryName" : "US" } ] } { "_id" : ObjectId("5e8ae5f8437efc8605595b67"), "details" : [ { "Name" : "Bob", "CountryName": "UK" } ] } { "_id" : ObjectId("5e8ae602437efc8605595b68"), "details" : [ { "Name" : "chris","CountryName" : "us" } ] } { "_id" : ObjectId("5e8ae60b437efc8605595b69"), "details" : [ { "Name" : "Mike","CountryName" : "UK" } ] }
以下是查找对象数组中多个匹配项的查询 −
> db.demo525.find( ... {"$and": [ ... { "details" : { "$elemMatch" :{ "Name": {$regex: new RegExp('^' + 'Chris', 'i')}}} }, ... { "details" : { "$elemMatch" :{ "CountryName": {$regex: new RegExp('^' + 'us', 'i')}}} } ... ]} ... )
这将产生以下输出 −
{ "_id" : ObjectId("5e8ae5ef437efc8605595b66"), "details" : [ { "Name" : "Chris", "CountryName" : "US" } ] } { "_id" : ObjectId("5e8ae602437efc8605595b68"), "details" : [ { "Name" : "chris", "CountryName" : "us" } ] }
广告