在 MongoDB 中按多个数组元素进行筛选?

mongodbdatabasebig data analytics更新于 2026/1/12 0:37:17

为此,您可以使用 $elemMatch 运算符。$elemMatch 运算符会匹配包含数组字段且至少有一个元素符合所有指定查询条件的文档。首先,我们创建一个包含文档的集合 −

> db.filterBySeveralElementsDemo.insertOne(
   "_id":100,
   "StudentDetails": [
      {
         "StudentName": "John",
         "StudentCountryName": "US",
      },
      {
         "StudentName": "Carol",
         "StudentCountryName": "UK"
      }
   ]
}
);
{ "acknowledged" : true, "insertedId" : 100 }
> db.filterBySeveralElementsDemo.insertOne(
   {
      "_id":101,
      "StudentDetails": [
         {
            "StudentName": "Sam",
            "StudentCountryName": "AUS",
         },
         {
            "StudentName": "Chris",
            "StudentCountryName": "US"
         }
      ]
   }
);
{ "acknowledged" : true, "insertedId" : 101 }

以下是使用 find() 方法显示集合中的所有文档的查询 −

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

这将产生以下输出 −

{
   "_id" : 100,
   "StudentDetails" : [
      {
         "StudentName" : "John",
         "StudentCountryName" : "US"
      },
      {
         "StudentName" : "Carol",
         "StudentCountryName" : "UK"
      }
   ]
}
{
   "_id" : 101,
   "StudentDetails" : [
      {
         "StudentName" : "Sam",
         "StudentCountryName" : "AUS"
      },
      {
         "StudentName" : "Chris",
         "StudentCountryName" : "US"
      }
   ]
}

以下是按多个数组元素进行过滤的查询 −

> db.filterBySeveralElementsDemo.find({ StudentDetails: { $elemMatch: { StudentName: 'Sam', StudentCountryName: 'AUS' }}}).pretty();

这将产生以下输出 −

{
   "_id" : 101,
   "StudentDetails" : [
      {
         "StudentName" : "Sam",
         "StudentCountryName" : "AUS"
      },
      {
         "StudentName" : "Chris",
         "StudentCountryName" : "US"
      }
   ]
}

相关文章