您可以使用$in运算符检查值是否在数组中。首先让我们创建一个包含文档的集合-
> db.valueInArrayDemo.insertOne({"UserName":"John","UserMessage":["Hi","Hello","Bye"]});{ "acknowledged" : true, "insertedId" : ObjectId("5cd684cf7924bb85b3f48959")}> db.valueInArrayDemo.insertOne({"UserName":"Larry","UserMessage":["Thank You","Amazing","Nice"]});{ "acknowledged" : true, "insertedId" : ObjectId("5cd684d27924bb85b3f4895a")}>db.valueInArrayDemo.insertOne({"UserName":"Carol","UserMessage":["Awesome","Bye","Cool"]});{ "acknowledged" : true, "insertedId" : ObjectId("5cd684d87924bb85b3f4895b")}
以下是在find()方法的帮助下显示集合中所有文档的查询-
> db.valueInArrayDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd684cf7924bb85b3f48959"), "UserName" : "John", "UserMessage" : [ "Hi", "Hello", "Bye" ] } { "_id" : ObjectId("5cd684d27924bb85b3f4895a"), "UserName" : "Larry", "UserMessage" : [ "Thank You", "Amazing", "Nice" ] } { "_id" : ObjectId("5cd684d87924bb85b3f4895b"), "UserName" : "Carol", "UserMessage" : [ "Awesome", "Bye", "Cool" ] }
以下是检查特定值是否在$in数组中的查询-
> db.valueInArrayDemo.find({UserMessage:{$in:["Bye"]}});
这将产生以下输出-
{ "_id" : ObjectId("5cd684cf7924bb85b3f48959"), "UserName" : "John", "UserMessage" : [ "Hi", "Hello", "Bye" ] } { "_id" : ObjectId("5cd684d87924bb85b3f4895b"), "UserName" : "Carol", "UserMessage" : [ "Awesome", "Bye", "Cool" ] }