如何找到具有与 MongoDB 查询中完全相同数组项的文档?
为此,请使用 $all 运算符。让我们首先创建一个文档集合 −
>db.findDocumentExactlySameInArrayDemo.insertOne({"TechnicalSubjects":["C++","Java","MongoDB"]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd69a5f57806ebf1256f12e") } >db.findDocumentExactlySameInArrayDemo.insertOne({"TechnicalSubjects":["MySQL","Java","MongoDB"]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd69ac057806ebf1256f12f") } >db.findDocumentExactlySameInArrayDemo.insertOne({"TechnicalSubjects":["C#","Python","MongoDB"]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd69ad457806ebf1256f130") } >db.findDocumentExactlySameInArrayDemo.insertOne({"TechnicalSubjects":["MySQL","C","MongoDB"]}); { "acknowledged" : true, "insertedId" : ObjectId("5cd69adf57806ebf1256f131") }
以下是使用 find() 方法显示集合中所有文档的查询 −
> db.findDocumentExactlySameInArrayDemo.find().pretty();
这将产生以下输出 −
{ "_id" : ObjectId("5cd69a5f57806ebf1256f12e"), "TechnicalSubjects" : [ "C++", "Java", "MongoDB" ] } { "_id" : ObjectId("5cd69ac057806ebf1256f12f"), "TechnicalSubjects" : [ "MySQL", "Java", "MongoDB" ] } { "_id" : ObjectId("5cd69ad457806ebf1256f130"), "TechnicalSubjects" : [ "C#", "Python", "MongoDB" ] } { "_id" : ObjectId("5cd69adf57806ebf1256f131"), "TechnicalSubjects" : [ "MySQL", "C", "MongoDB" ] }
以下是查找具有与查询中完全相同数组项的文档的查询 −
> db.findDocumentExactlySameInArrayDemo.find({"TechnicalSubjects": { "$all": ["MySQL","Java","MongoDB"] }});
这将产生以下输出 −
{ "_id" : ObjectId("5cd69ac057806ebf1256f12f"), "TechnicalSubjects" : [ "MySQL", "Java", "MongoDB" ] }
广告