查询MongoDB的子集以获取记录

您可以使用$all运算符。首先让我们创建一个包含文档的集合-

> db.subsetOfAnArrayDemo.insertOne({"StudentProgrammingSkills":
   ["Java","MongoDB","MySQL","C++","Data Structure","Algorithm","Python","Oracle","SQL Server"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cb9d1e1895c4fd159f80804")
}

以下是在find()方法的帮助下显示集合中所有文档的查询-

> db.subsetOfAnArrayDemo.find().pretty();

这将产生以下输出-

{
   "_id" : ObjectId("5cb9d1e1895c4fd159f80804"),
   "StudentProgrammingSkills" : [
      "Java",
      "MongoDB",
      "MySQL",
      "C++",
      "Data Structure",
      "Algorithm",
      "Python",
      "Oracle",
      "SQL Server"
   ]
}

以下是获取数组子集的查询-

> db.subsetOfAnArrayDemo.find({ StudentProgrammingSkills:
   { $all: [ 'MongoDB', 'MySQL' ] } } ).pretty();

这将产生以下输出-

{
   "_id" : ObjectId("5cb9d1e1895c4fd159f80804"),
   "StudentProgrammingSkills" : [
      "Java",
      "MongoDB",
      "MySQL",
      "C++",
      "Data Structure",
      "Algorithm",
      "Python",
      "Oracle",
      "SQL Server"
   ]
}