2012-03-04 56 views
0

我有一个是通过使用.sort({ rating : -1 })如何在一些文档错过MongoDB中的密钥时进行排序?

我有很多的不具有任何等级的物品等级分类的物品(在DB的一面,他们甚至还没有评级键)。在前端,我告诉他们的1

0.5的速度。当我的物品进行分类,我现在有这个命令:

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更高的0.5评级(在先前的排序中甚至更低)。所以,我想这样的事情:

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。

任何诡计?有任何想法吗 ?

+0

对此深感抱歉,其实我倒在那些和使用一些原型现在是mongoid。 – Hartator 2012-03-06 14:33:50

回答

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 } 
相关问题