java - MongoDB,Java,按第一个数组条目排序

标签 java mongodb aggregation-framework

我试图在通过 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/

相关文章:

angularjs - 环回中的动态 datasource.json

node.js - MongoDB中数组元素的插入顺序

Mongodb:如何使用一个查询获取不同集合中文档的数量?

java - 将 war 文件转换为可执行文件

java - 如何使用 Struts 2 gzip ajax 请求?

java - 如何在 Java 中实现许多类通用的自定义方法?

json - 如何使用 Go 后端和 ReactJS 前端在 MongoDB 中插入 markdown 代码

mongodb展开嵌套在文档数组中的数组

javascript - 按日期分组 Mongo 聚合

java - 单击按钮应调用一个选项卡 Pane (动态),其中包含文本面板