在使用 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"
   ]
}

更新于: 2019 年 7 月 30 日

387 次浏览

启动你的 职业生涯

完成课程获得认证

立即开始
广告