为此,请使用$和$正则表达式。的$和执行一个或多个表达式,并选择满足 阵列中所有表达式的文件的阵列上的逻辑与操作。
让我们创建一个包含文档的集合-
> 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" } ] }