MongoDB,Java,按第一个数组条目排序 [英] MongoDB, Java, sort by first array entry
问题描述
我正在尝试通过Java API在MongoDB上执行查找后对值进行排序。结果列表包含以下条目:
I'm trying to sort values after executing a find on my MongoDB by Java API. The result list contains the following entries:
{
"_id": "P17-223",
"property": "P17",
"itemid": 223,
"labels": [
{
"language": "en",
"value": "Greenland"
},
{
"language": "es",
"value": "Groenlandia"
},
{
"language": "de",
"value": "Grönland"
}
]
}
我想按数组标签的第一个条目排序:
I want to sort by the first entry of the array labels:
DBCursor cursor = getCollection().find(query);
BasicDBObject orderBy = new BasicDBObject("labels[0].value", 1);
cursor.sort(orderBy);
此代码不对游标值进行排序。你能帮助我吗?
Cursor values are not sorted by this code. Can you help me?
推荐答案
你试过吗
BasicDBObject orderBy = new BasicDBObject("labels.0.value", 1);
这并不明显,但是MongoDB文档却没有提到它。使用$符号匹配第一个项目,但指定数组元素编号似乎有效。如果有人有更好的文档描述行为,请回复链接。
It's not obvious, but the MongoDB documentation eludes to it. Using the $ sign matches the first item, but specifying the array element number seems to work. If anyone has a better document describing the behavior, please reply with the link.
来自文档
更新数组中的文档
Update Documents in an Array
The positional $ operator facilitates updates to arrays that contain embedded
documents. Use the positional $ operator to access the fields in the embedded
documents with the dot notation on the $ operator.
db.collection.update( { <query selector> }, { <update operator>: { "array.$.field" : value } } )
文档是这里
这篇关于MongoDB,Java,按第一个数组条目排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!