如果所有键都作为字段存在,则在MongoDB中过滤文档?
为此,请使用$all,它将查找包含数组中所有元素(如“键”)的文档。首先让我们创建一个包含文档的集合-
> db.demo17.insertOne({"ListOfSubject":["MySQL","MongoDB","Java"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e13847255d0fc6657d21f0a") } > db.demo17.insertOne({"ListOfSubject":["C","Python","Java"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e13847e55d0fc6657d21f0b") } > db.demo17.insertOne({"ListOfSubject":["C++","MongoDB","PL/SQL"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e13849255d0fc6657d21f0c") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.demo17.find();
这将产生以下输出-
{ "_id" : ObjectId("5e13847255d0fc6657d21f0a"), "ListOfSubject" : [ "MySQL", "MongoDB", "Java" ] } { "_id" : ObjectId("5e13847e55d0fc6657d21f0b"), "ListOfSubject" : [ "C", "Python", "Java" ] } { "_id" : ObjectId("5e13849255d0fc6657d21f0c"), "ListOfSubject" : [ "C++", "MongoDB", "PL/SQL" ] }
如果所有键都作为字段存在,这是用于过滤文档的查询-
> db.demo17.find({"ListOfSubject": { "$all": ["C++","PL/SQL","MongoDB"] } });
这将产生以下输出-
{ "_id" : ObjectId("5e13849255d0fc6657d21f0c"), "ListOfSubject" : [ "C++", "MongoDB", "PL/SQL" ] }