MongoDB:按数组索引排序 [英] MongoDB: Sort by array index

查看:75
本文介绍了MongoDB:按数组索引排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文档,其中的数组字段包含值列表,我想按数组中的第一个元素进行排序.

I have a document with an array field that contains a list of values and I would like to sort by the first element in the array.

{
   field1 : "bla",
   field2 : "bla",
   field3 : "bla",
   someArray : [123, 456, 789]
}

我试图这样查询:

db.testCollection.find({}).sort({"someArray[0]" : 1})

但这似乎没有任何效果,并且排序被忽略了.

But this does not seem to have any effect and the sort gets ignored.

有什么办法可以做到吗?

Is there any way this can be done?

推荐答案

是的,按someArray的第一个元素以递增顺序对集合进行排序的方式是:

Yes, the way to sort your collection by the first element of someArray in increasing order is:

db.testCollection.find().sort({"someArray.0": 1})

这里不需要聚合框架.你非常亲密!

There is no need for the aggregation framework here. You were very close!

这篇关于MongoDB:按数组索引排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆