如何使用数组的最后一个元素对集合进行排序

如何使用数组的最后一个元素对集合进行排序

本文介绍了如何使用数组的最后一个元素对集合进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我的问题是,我在下面有一个集合,_id被忽略了

My problem is that, i have a collection below, _id is ignored

{ "value" : -10, "r" : [ { "v" : 1 }, { "v" : 3 } ] }
{ "value" : 2, "r" : [ { "v" : 4 }, { "v" : 1 } ] }
{ "value" : -100, "r" : [ { "v" : 4 }, { "v" : 1 }, { "v" : 10 } ] }
{ "value" : -3, "r" : [ ] }

然后我要根据数组r的最后一个值对它进行排序,也就是说,我想在下面得到一个结果,

And i what to sort it by the last value of array r, that is to say, i want to have a result below,

{ "value" : -3, "r" : [ ] } # this one should be either the first one or the last one
{ "value" : 2, "r" : [ { "v" : 4 }, { "v" : 1 } ] }
{ "value" : -10, "r" : [ { "v" : 1 }, { "v" : 3 } ] }
{ "value" : -100, "r" : [ { "v" : 4 }, { "v" : 1 }, { "v" : 10 } ] }

我知道我可以按数组r的第一个值排序

I know that i can sort by the first vaue of the array r by

db.my.find().sort({'r.0.v': 1})

但是怎么才能用最后的值呢?

But how can do it by the last value?

并且,如果使用下面的mongoengine模型

And, if with its mongoengine model below

class V(EmbeddedDocument):
    v = IntField()

class M(Document):
    value = IntFiled
    r = ListField(EmbeddedDocumentField(V))

我应该如何使用mongoengine? IntField可能还有其他字段,例如DateTimeFieldStringField ...

How should i do with mongoengine? IntField maybe other fields such as DateTimeField, StringField ...

谢谢

推荐答案

如果可能的话,我建议您总是(双重)存储要排序的值.将其放在数组和第二个字段中.每当将新值推送到数组(或存储数组)时,都添加一个与数组中的最后一个值"相对应的新字段,然后对其进行索引和排序.在下面的示例中,我将其命名为lastR:

If possible, I'd suggest you just always (double) store the value you want to sort on. Put it in the array and in a second field. Whenever you push a new value to the array (or store the array), add a new field corresponding to the "last value in array" and then index and sort on that. In the example below, I called it lastR:

{ "value" : -10, "r" : [ { "v" : 1 }, { "v" : 3 } ], "lastR": 3 }
{ "value" : 2, "r" : [ { "v" : 4 }, { "v" : 1 } ], "lastR": 1 }
{ "value" : -100, "r" : [ { "v" : 4 }, { "v" : 1 }, { "v" : 10 } ], "lastR": 10 }
{ "value" : -3, "r" : [ ] }

创建索引:

db.so.ensureIndex({lastR: 1})

然后使用:

> db.so.find().sort({lastR: 1})
{ "_id" : ObjectId("5203a1c83c5438af60de63a1"), "value" : -3, "r" : [ ] }
{ "_id" : ObjectId("5203a1ad3c5438af60de639f"), "value" : 2, "r" : [ { "v" : 4 }, { "v" : 1 } ], "lastR" : 1 }
{ "_id" : ObjectId("5203a1d33c5438af60de63a2"), "value" : -10, "r" : [ { "v" : 1 }, { "v" : 3 } ], "lastR" : 3 }
{ "_id" : ObjectId("5203a1b73c5438af60de63a0"), "value" : -100, "r" : [ { "v" : 4 }, { "v" : 1 }, { "v" : 10 } ], "lastR" : 10 }

与尝试使用聚合解决方案相比,它将具有更多的用途和可扩展性(聚合解决方案的结果集将有16MB的限制,并且在需要处理投影时检索复杂的文档要复杂得多).

It will be far more versatile and expandable than trying to use an aggregation solution (which will have a 16MB limit to the result set and makes it far more complex to retrieve complex documents when needing to deal with a projection).

这篇关于如何使用数组的最后一个元素对集合进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 19:11