要获得与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" ] }