【问题标题】:Fetch mongo documents based on date根据日期获取 mongo 文档
【发布时间】:2015-05-28 06:22:07
【问题描述】:

我们正在插入带有标识符的 mongo 文档,并且文档中有一个子数组。

insert 1 :

db.test.insert(
   {
        "companyId" : "123",
        "persons" : [
                {
                        "joiningDate" : NumberLong("1431674741623"),
                         "name" : "Rajesh"
                }
        ],

})

insert 2 :

db.test.insert(
   {
        "companyId" : "123",
        "persons" : [
                {
                        "joiningDate" : NumberLong("1431674741653"),
                         "name" : "Rahul"
                }
        ],

})

我想根据公司ID检索公司详细信息并将人员合并到一个数组列表中,并根据加入日期对人员进行排序。

目前我可以使用 QueryBuilder 检索数据,但我无法根据日期对人员进行排序。我可以使用 java 比较器来做同样的事情,但我正在寻找是否有来自 mongo db java 的 API可以用来获取相同的驱动程序。

谢谢。

【问题讨论】:

  • 为什么 'joiningDate' 数据类型是 NumberLong??
  • @gypsyCoder 它应该是纪元时间 :)
  • @gypsyCoder:这也是我注意到的一个问题,日期在 mongo Db 中设置为 NumberLong。在 java 代码中,它是使用 long in ms 值构造的 util 包的一部分。
  • @Amz 你在使用 java.util.Date() 吗??
  • @gypsyCoder:是的,我是,

标签: mongodb mongodb-java


【解决方案1】:

你应该使用mongo aggregation,比如首先使用$unwindpersons数组然后排序persons.joiningDate然后group with push如下:

db.test.aggregate({
  "$match": {
    "companyId": "123" // match companyId
  }
}, {
  "$unwind": "$persons" //unwind person array
}, {
  "$sort": {
    "persons.joiningDate": -1 //sort joining date
  }
}, {
  "$group": {
    "_id": "$companyId",
    "persons": {
      "$push": "$persons" //push all sorted data into persons
    }
  }
}).pretty()

要将此代码转换为 java 使用 mongo java aggregation as

// unwind  persons
DBObject unwind = new BasicDBObject("$unwind", "$persons");
// create  pipeline operations, with the $match companyId
DBObject match = new BasicDBObject("$match", new BasicDBObject("companyId", "123"));
// sort persons by joining date 
DBObject sortDates = new BasicDBObject("$sort", new BasicDBObject("persons.joiningDate", -1)); // -1 and 1 descending or ascending resp.
// Now the $group operation  
DBObject groupFields = new BasicDBObject("_id", "$companyId");
groupFields.put("persons", new BasicDBObject("$push", "$persons"));
DBObject group = new BasicDBObject("$group", groupFields);
// run aggregation
List < DBObject > pipeline = Arrays.asList(match, unwind,sortDates, group);
AggregationOutput output = test.aggregate(pipeline);
for(DBObject result: output.results()) {
  System.out.println(result);
}

【讨论】:

    猜你喜欢
    • 2020-07-05
    • 1970-01-01
    • 1970-01-01
    • 2021-09-12
    • 1970-01-01
    • 2017-01-14
    • 2018-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多