当一些文档错过MongoDB中的密钥时如何排序?

时间:2012-03-04 00:50:19

标签: mongodb mongoid

我的文章按其评分使用.sort( { rating : -1 } )

排序

我有很多文章没有任何评级(在DB方面,他们甚至没有评级键)。在前端,我以0.5的1显示它们。

当我对文章进行排序时,我现在有了这个顺序:

1 1 0.89 0.7 0.5 0.2 0.1 0 0 0 0 0 no_key no_key no_key no_key no_key no_key...

但是,我想考虑到no_key的评分是0.5而不是0(在之前的排序中甚至更低)。所以,我想要这样的事情:

1 1 0.89 0.7 0.5 no_key no_key no_key no_key no_key no_key... 0.2 0.1 0 0 0 0 0 

我希望避免将未评级文章的缺失评级密钥填写0.5。

任何诡计?任何想法?

1 个答案:

答案 0 :(得分:3)

因此,这需要三个单独的查询,但在聚合框架(http://www.mongodb.org/display/DOCS/Aggregation+Framework)出现之前,它可能是最好的方式:

> db.test.save({rating:1});
> db.test.save({rating:2});
> db.test.save({rating:3});
> db.test.save({rating:4});
> db.test.save({rating:0.5});
> db.test.save({rating:0});
> db.test.save({rating:0}); 
> db.test.save({rating:0});
> db.test.save({rating:-1});
> db.test.save({});
> db.test.save({});
> db.test.save({});
> db.test.find({rating:{$gte:.5}}).sort({rating:-1});
{ "_id" : ObjectId("4f52c707621918e231bc55da"), "rating" : 4 }
{ "_id" : ObjectId("4f52c705621918e231bc55d9"), "rating" : 3 }
{ "_id" : ObjectId("4f52c703621918e231bc55d8"), "rating" : 2 }
{ "_id" : ObjectId("4f52c700621918e231bc55d7"), "rating" : 1 }
{ "_id" : ObjectId("4f52c70b621918e231bc55db"), "rating" : 0.5 }
> db.test.find({rating:{$exists:false}});
{ "_id" : ObjectId("4f52c718621918e231bc55e0") }
{ "_id" : ObjectId("4f52c719621918e231bc55e1") }
{ "_id" : ObjectId("4f52c71a621918e231bc55e2") }
> db.test.find({rating:{$lt:.5}}).sort({rating:-1});
{ "_id" : ObjectId("4f52c70e621918e231bc55dc"), "rating" : 0 }
{ "_id" : ObjectId("4f52c712621918e231bc55dd"), "rating" : 0 }
{ "_id" : ObjectId("4f52c712621918e231bc55de"), "rating" : 0 }
{ "_id" : ObjectId("4f52c714621918e231bc55df"), "rating" : -1 }