MongoDB的“ $ and”运算符用于子集合来获取文档?
要获取文档,请在MongoDB中使用$in代替$and。首先让我们创建一个包含文档的集合-
> db.demo83.insertOne( ... { ... "Details":[ ... { ... "Name":"Chris", ... "Subject":[ ... "MySQL", ... "MongoDB" ... ] ... }, ... { ... "Name":"David", ... "Subject":[ ... "Java", ... "C" ... ] ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e2bfd2271bf0181ecc422a3") } > db.demo83.insertOne( ... { ... "Details":[ ... { ... "Name":"Bob", ... "Subject":[ ... "C++", ... "Python" ... ] ... }, ... { ... "Name":"John", ... "Subject":[ ... "Spring", ... "Hibernate" ... ] ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e2bfd4571bf0181ecc422a4") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo83.find();
这将产生以下输出-
{ "_id" : ObjectId("5e2bfd2271bf0181ecc422a3"), "Details" : [ { "Name" : "Chris", "Subject" : [ "MySQL", "MongoDB" ] }, { "Name" : "David", "Subject" : [ "Java", "C" ] } ] } { "_id" : ObjectId("5e2bfd4571bf0181ecc422a4"), "Details" : [ { "Name" : "Bob", "Subject" : [ "C++", "Python" ] }, { "Name" : "John", "Subject" : [ "Spring", "Hibernate" ] } ] }
以下是使用$in查找文档的查询-
> db.demo83.find({ "Details" : { "$elemMatch" : {"Name" :"Chris" , "Subject":{"$in":["MongoDB"]}}}});
这将产生以下输出-
{ "_id" : ObjectId("5e2bfd2271bf0181ecc422a3"), "Details" : [ { "Name" : "Chris", "Subject" : [ "MySQL", "MongoDB" ] }, { "Name" : "David", "Subject" : [ "Java", "C" ] } ] }