如何在 MongoDB 数组中执行 AND 查询?
要在 MongoDB 中获得与 AND 相同的结果,请使用 $all 运算符。我们首先使用文档创建一个集合 -
> db.andQueryDemo.insertOne({"StudentName":"Carol Taylor","FavouriteSubject":["C","Java","MongoDB","MySQL"]}); { "acknowledged" : true, "insertedId" : ObjectId("5cc73e7a8f9e6ff3eb0ce433") } > db.andQueryDemo.insertOne({"StudentName":"David Miller","FavouriteSubject":["C++","Java","MongoDB","SQL Server"]}); { "acknowledged" : true, "insertedId" : ObjectId("5cc73ea48f9e6ff3eb0ce434") } > db.andQueryDemo.insertOne({"StudentName":"Carol Taylor","FavouriteSubject":["Python","PL/SQL"]}); { "acknowledged" : true, "insertedId" : ObjectId("5cc73ed38f9e6ff3eb0ce435") }
以下查询利用 find() 方法显示集合中的所有文档 -
> db.andQueryDemo.find().pretty();
这将生成以下输出 -
{ "_id" : ObjectId("5cc73e7a8f9e6ff3eb0ce433"), "StudentName" : "Carol Taylor", "FavouriteSubject" : [ "C", "Java", "MongoDB", "MySQL" ] } { "_id" : ObjectId("5cc73ea48f9e6ff3eb0ce434"), "StudentName" : "David Miller", "FavouriteSubject" : [ "C++", "Java", "MongoDB", "SQL Server" ] } { "_id" : ObjectId("5cc73ed38f9e6ff3eb0ce435"), "StudentName" : "Carol Taylor", "FavouriteSubject" : [ "Python", "PL/SQL" ] }
以下查询使用 $all 在 MongoDB 数组中执行 AND 查询。在此,我们显示的数组将“Java”和“MongoDB”都显示为 FavouriteSubject -
> db.andQueryDemo.find({FavouriteSubject:{$all:["Java","MongoDB"]}}).pretty();
这将生成以下输出 -
{ "_id" : ObjectId("5cc73e7a8f9e6ff3eb0ce433"), "StudentName" : "Carol Taylor", "FavouriteSubject" : [ "C", "Java", "MongoDB", "MySQL" ] } { "_id" : ObjectId("5cc73ea48f9e6ff3eb0ce434"), "StudentName" : "David Miller", "FavouriteSubject" : [ "C++", "Java", "MongoDB", "SQL Server" ] }
广告