您可以在一级数组上使用$in运算符代替$elemMatch。语法如下
db.yourCollectionName.find({yourFieldName:{$in:["yourValue"]}}).pretty();
首先让我们创建一个包含文档的集合
>db.firstLevelArrayDemo.insertOne({"StudentName":"Chris","StudentTechnicalSkills":["Mongo DB","MySQL","SQL Server"]}); { "acknowledged" : true, "insertedId" : ObjectId("5ca2360f66324ffac2a7dc71") } >db.firstLevelArrayDemo.insertOne({"StudentName":"Robert","StudentTechnicalSkills":["C","J ava","C++"]}); { "acknowledged" : true, "insertedId" : ObjectId("5ca2362766324ffac2a7dc72") }
以下是在find()
方法的帮助下显示集合中所有文档的查询
> db.firstLevelArrayDemo.find().pretty();
这将产生以下输出
{ "_id" : ObjectId("5ca2360f66324ffac2a7dc71"), "StudentName" : "Chris", "StudentTechnicalSkills" : [ "MongoDB", "MySQL", "SQL Server" ] } { "_id" : ObjectId("5ca2362766324ffac2a7dc72"), "StudentName" : "Robert", "StudentTechnicalSkills" : [ "C", "Java", "C++" ] }
以下是要在第一级数组上进行匹配的查询
> db.firstLevelArrayDemo.find({StudentTechnicalSkills:{$in:["MongoDB"]}}).pretty();
这将产生以下输出
{ "_id" : ObjectId("5ca2360f66324ffac2a7dc71"), "StudentName" : "Chris", "StudentTechnicalSkills" : [ "MongoDB", "MySQL", "SQL Server" ] }