MongoDB查询检查数组属性中的值?
你可以使用 $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" ] }
广告