我试图在通过 Java API 在我的 MongoDB 上执行查找后对值进行排序。结果列表包含以下条目:
{
"_id": "P17-223",
"property": "P17",
"itemid": 223,
"labels": [
{
"language": "en",
"value": "Greenland"
},
{
"language": "es",
"value": "Groenlandia"
},
{
"language": "de",
"value": "Grönland"
}
]
我想按数组标签的第一个条目排序:
DBCursor cursor = getCollection().find(query);
BasicDBObject orderBy = new BasicDBObject("labels[0].value", 1);
cursor.sort(orderBy);
游标值不按此代码排序。你能帮帮我吗?
最佳答案
你试过吗
BasicDBObject orderBy = new BasicDBObject("labels.0.value", 1);
这不是很明显,但是 MongoDB 文档避开了它。使用 $ 符号匹配第一项,但指定数组元素编号似乎可行。如果有人有更好的文档来描述该行为,请回复链接。
来自文档
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 } } )
文档是 here
关于java - MongoDB,Java,按第一个数组条目排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24911935/