如何使用MongoDB查找具有不同顺序值的精确数组匹配?
要查找具有不同顺序值的精确数组匹配,可以使用$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
]
}