如何查找与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" ] }