如何使用 MongoDB 查找不同顺序的精确数组匹配值?

mongodbdatabasebig data analytics

要查找不同顺序的精确数组匹配值,可以使用 $all 运算符。让我们创建一个包含文档的集合。以下是查询语句

>db.exactMatchArrayDemo.insertOne({"StudentName":"David","StudentAge":22,"StudentGameScores":[45,78,98]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9c94702d6669774125246c")
}
>db.exactMatchArrayDemo.insertOne({"StudentName":"Chris","StudentAge":23,"StudentGameScores":[45,78]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c9c94a42d6669774125246d")
}

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

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

这将产生以下输出 −

{
   "_id" : ObjectId("5c9c94702d6669774125246c"),
   "StudentName" : "David",
   "StudentAge" : 22,
   "StudentGameScores" : [
      45,
      78,
      98
   ]
}
{
   "_id" : ObjectId("5c9c94a42d6669774125246d"),
   "StudentName" : "Chris",
   "StudentAge" : 23,
   "StudentGameScores" : [
      45,
      78
   ]
}

以下是查找精确数组匹配的查询

> db.exactMatchArrayDemo.find({ "StudentGameScores": { "$size" : 2, "$all": [ 78, 45 ] } }).pretty();

这将产生以下输出 −

{
   "_id" : ObjectId("5c9c94a42d6669774125246d"),
   "StudentName" : "Chris",
   "StudentAge" : 23,
   "StudentGameScores" : [
      45,
      78
   ]
}

以下查询用于查找精确匹配的数组,但顺序无关紧要。我们设置了不同的大小,以获取包含 3 个值的字段"StudentGameScores"

> db.exactMatchArrayDemo.find({ "StudentGameScores": { "$size" : 3, "$all": [ 78, 45 ] } }).pretty();

这将产生以下输出 −

{
   "_id" : ObjectId("5c9c94702d6669774125246c"),
   "StudentName" : "David",
   "StudentAge" : 22,
   "StudentGameScores" : [
      45,
      78,
      98
   ]
}

相关文章