在 MongoDB 中,如果所有键都存在于字段中,则筛选文档?
为此,请使用 $all,它将查找包含与“keys”这样的数组中所有元素的文档。让我们首先创建一个包含文档的集合 -
> 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" ] }
广告