通过使用skip和limit进行排序来获取记录时遇到重复记录的问题:
收集数据:
{
"_id" : ObjectId("594b507c9b9469ec9da6a78b"),
"name" : "F",
"percentage" : 60.0,
"weightedFilter" : 2.0,
"like" : 1.0,
"attraction" : 1.0
}
{
"_id" : ObjectId("594b507c9b9469ec9da6a78c"),
"name" : "I",
"percentage" : 80.0,
"weightedFilter" : 0.0,
"like" : 1.0,
"attraction" : 1.0
}
{
"_id" : ObjectId("594b507c9b9469ec9da6a78d"),
"name" : "J",
"percentage" : 80.0,
"weightedFilter" : 1.0,
"like" : 1.0,
"attraction" : 1.0
}
{
"_id" : ObjectId("594b507c9b9469ec9da6a78e"),
"name" : "A",
"percentage" : 100.0,
"weightedFilter" : 0.0,
"like" : 1.0,
"attraction" : 1.0
}
{
"_id" : ObjectId("594b507c9b9469ec9da6a78f"),
"name" : "K",
"percentage" : 80.0,
"weightedFilter" : 1.0,
"like" : 1.0,
"attraction" : 1.0
}
{
"_id" : ObjectId("594b507c9b9469ec9da6a790"),
"name" : "G",
"percentage" : 60.0,
"weightedFilter" : 2.0,
"like" : 1.0,
"attraction" : 1.0
}
{
"_id" : ObjectId("594b507c9b9469ec9da6a791"),
"name" : "H",
"percentage" : 80.0,
"weightedFilter" : 0.0,
"like" : 1.0,
"attraction" : 1.0
}
{
"_id" : ObjectId("594b507c9b9469ec9da6a792"),
"name" : "B",
"percentage" : 100.0,
"weightedFilter" : 0.0,
"like" : 1.0,
"attraction" : 1.0
汇总查询1:
db.testing.aggregate([{$sort : { "like": -1 }},{$skip : 0},{$limit:4}]);
输出:
{
"_id" : ObjectId("594b507c9b9469ec9da6a78d"),
"name" : "J",
"percentage" : 80.0,
"weightedFilter" : 1.0,
"like" : 1.0,
"attraction" : 1.0
}
{
"_id" : ObjectId("594b507c9b9469ec9da6a78b"),
"name" : "F",
"percentage" : 60.0,
"weightedFilter" : 2.0,
"like" : 1.0,
"attraction" : 1.0
}
{
"_id" : ObjectId("594b507c9b9469ec9da6a78c"),
"name" : "I",
"percentage" : 80.0,
"weightedFilter" : 0.0,
"like" : 1.0,
"attraction" : 1.0
}
{
"_id" : ObjectId("594b507c9b9469ec9da6a78e"),
"name" : "A",
"percentage" : 100.0,
"weightedFilter" : 0.0,
"like" : 1.0,
"attraction" : 1.0
}
汇总查询2:
db.testing.aggregate([{$sort : { "like": -1 }},{$skip : 4},{$limit:4}]);
{
"_id" : ObjectId("594b507c9b9469ec9da6a78b"),
"name" : "F",
"percentage" : 60.0,
"weightedFilter" : 2.0,
"like" : 1.0,
"attraction" : 1.0
}
{
"_id" : ObjectId("594b507c9b9469ec9da6a78c"),
"name" : "I",
"percentage" : 80.0,
"weightedFilter" : 0.0,
"like" : 1.0,
"attraction" : 1.0
}
{
"_id" : ObjectId("594b507c9b9469ec9da6a78e"),
"name" : "A",
"percentage" : 100.0,
"weightedFilter" : 0.0,
"like" : 1.0,
"attraction" : 1.0
}
{
"_id" : ObjectId("594b507c9b9469ec9da6a792"),
"name" : "B",
"percentage" : 100.0,
"weightedFilter" : 0.0,
"like" : 1.0,
"attraction" : 1.0
}
结论:
更改跳过0-> 4时,获得名称为 F,I,A
的重复记录不知道为什么会这样?
答案 0 :(得分:5)
根据您的收集数据,您按密钥排序,具有共同的值。
在您使用的第一个聚合聚合中(跳过,限制)=> (0,4)在这种情况下,mongo按顺序从所有文档中排序文档,并对结果进行排序。
在第二次聚合中,您再次使用(skip,limit)=> (4,4)在这种情况下,mongo正在对所有文档进行排序,其中文档可以重复,同时在密钥中具有相同的值。
因此,在根据您的数据进行排序后,您应该根据需要使用任何唯一键(“_id”或“name”)对数据进行排序 注意:密钥应该是唯一的
如下所示
db.testing.aggregate([
{
$sort : {
"percentage": -1,
"_id" : 1
},
},
{
$skip : 0
},
{
$limit:4
}
]);