在MongoDB的列表查询中至少获得一个匹配项?

使用$in运算符至少获取一个匹配项。首先让我们创建一个包含文档的集合-

> db.atleastOneMatchDemo.insertOne({"StudentFavouriteSubject":["MySQL","MongoDB"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd2db5db64f4b851c3a13ce")
}
> db.atleastOneMatchDemo.insertOne({"StudentFavouriteSubject":["Java","C","MongoDB"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd2db71b64f4b851c3a13cf")
}
> db.atleastOneMatchDemo.insertOne({"StudentFavouriteSubject":["Python","C++","SQL Server"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd2db87b64f4b851c3a13d0")
}
>db.atleastOneMatchDemo.insertOne({"StudentFavouriteSubject":["Ruby","Javascript","C#","MySQL"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd2dba9b64f4b851c3a13d1")
}

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

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

这将产生以下输出-

{
   "_id" : ObjectId("5cd2db5db64f4b851c3a13ce"),
   "StudentFavouriteSubject" : [
      "MySQL",
      "MongoDB"
   ]
}
{
   "_id" : ObjectId("5cd2db71b64f4b851c3a13cf"),
   "StudentFavouriteSubject" : [
      "Java",
      "C",
      "MongoDB"
   ]
}
{
   "_id" : ObjectId("5cd2db87b64f4b851c3a13d0"),
   "StudentFavouriteSubject" : [
      "Python",
      "C++",
      "SQL Server"
   ]
}
{
   "_id" : ObjectId("5cd2dba9b64f4b851c3a13d1"),
   "StudentFavouriteSubject" : [
      "Ruby",
      "Javascript",
      "C#",
      "MySQL"
   ]
}

以下是获取至少一个匹配项的查询-

>db.atleastOneMatchDemo.find({"StudentFavouriteSubject":{"$in":["MongoDB","MySQL"]}}).pretty();

这将产生以下输出-

{
   "_id" : ObjectId("5cd2db5db64f4b851c3a13ce"),
   "StudentFavouriteSubject" : [
      "MySQL",
      "MongoDB"
   ]
}
{
   "_id" : ObjectId("5cd2db71b64f4b851c3a13cf"),
   "StudentFavouriteSubject" : [
      "Java",
      "C",
      "MongoDB"
   ]
}
{
   "_id" : ObjectId("5cd2dba9b64f4b851c3a13d1"),
   "StudentFavouriteSubject" : [
      "Ruby",
      "Javascript",
      "C#",
      "MySQL"
   ]
}