MongoDB: $nin 和 $in 在 $elemMatch 中无法配合使用以获取包含主题“MongoDB”但又不包含“Java”的文档
对于这种获取,仅使用 $nin 和 $in。让我们创建一个包含文档的集合 −
> db.demo140.insertOne({"Id":101,"Subjects":["MongoDB","MySQL"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e31c149fdf09dd6d08539a9") } > db.demo140.insertOne({"Id":102,"Subjects":["MongoDB","Java"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e31c14cfdf09dd6d08539aa") } > db.demo140.insertOne({"Id":103,"Subjects":["MongoDB","PL/SQL"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e31c157fdf09dd6d08539ab") } > db.demo140.insertOne({"Id":104,"Subjects":["MongoDB","SQL Server"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e31c163fdf09dd6d08539ac") } > db.demo140.insertOne({"Id":105,"Subjects":["C","C++"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e31c16ffdf09dd6d08539ad") }
使用 find() 方法显示集合中的所有文档 −
> db.demo140.find();
这将产生以下输出 −
{ "_id" : ObjectId("5e31c149fdf09dd6d08539a9"), "Id" : 101, "Subjects" : [ "MongoDB", "MySQL" ] } { "_id" : ObjectId("5e31c14cfdf09dd6d08539aa"), "Id" : 102, "Subjects" : [ "MongoDB", "Java" ] } { "_id" : ObjectId("5e31c157fdf09dd6d08539ab"), "Id" : 103, "Subjects" : [ "MongoDB", "PL/SQL" ] } { "_id" : ObjectId("5e31c163fdf09dd6d08539ac"), "Id" : 104, "Subjects" : [ "MongoDB", "SQL Server" ] } { "_id" : ObjectId("5e31c16ffdf09dd6d08539ad"), "Id" : 105, "Subjects" : [ "C", "C++" ] }
以下是对包含主题“MongoDB”但又不包含“Java”的文档的查询 −
> db.demo140.find({$and:[{Subjects:{$in:['MongoDB']}}, {Subjects:{$nin:['Java']}}]}).toArray();
这将产生以下输出 −
[ { "_id" : ObjectId("5e31c149fdf09dd6d08539a9"), "Id" : 101, "Subjects" : [ "MongoDB", "MySQL" ] }, { "_id" : ObjectId("5e31c157fdf09dd6d08539ab"), "Id" : 103, "Subjects" : [ "MongoDB", "PL/SQL" ] }, { "_id" : ObjectId("5e31c163fdf09dd6d08539ac"), "Id" : 104, "Subjects" : [ "MongoDB", "SQL Server" ] } ]
广告