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" ] } ] }
广告