复杂的Mongo Shell命令转换为Java代码

时间:2016-04-16 18:08:02

标签: java mongodb mongo-shell

我有一个类似于

的Mongoshell查询
db.RemoteMongoData.aggregate([
        {$group: {
                "_id":"$IMEI Number",
        "Longitude":{"$last":"$Longitude"},
        "Latitude":{"$last":"$Latitude"},
        "Address":{"$last":"$Address"},
        "Timestamp":{"$last":"$Timestamp"},
            }},
        {$project: {
                 "IMEI Number":"$_id",
         "Longitude":"$Longitude",
         "Latitude":"$Latitude",
         "Address":"$Address",
         "Timestamp":"$Timestamp",
              }},
        {$sort: {
                'date': -1
            }}
    ])

我想知道如何转换此查询,以便可以使用java执行它。

转换"经度":{" $ last":" $ Longitude"}进入等效的java对象是困扰我的。 请帮忙.. 从网上可用的来源,我写了一个类似

的查询
DBObject group = new BasicDBObject("$group", new BasicDBObject("_id", "$IMEI Number")
    .append("Longitude", new BasicDBObject("$last","$longitude"))
    .append("Latitude", new BasicDBObject("$last","$latitude"))
    .append("Address", new BasicDBObject("$last","$address"))
    .append("Timestamp", new BasicDBObject("$last","$timestamp")));

    DBObject project = new BasicDBObject("$project", new BasicDBObject("IMEI Number","$_id")
    .append("Longitude","Longitude")
    .append("Latitude","Latitude")
    .append("Address","Address")
    .append("Timestamp","Timestamp"));

    DBObject sort = new BasicDBObject("$sort", new BasicDBObject("date",-1));

    AggregationOutput output = dbCollection.aggregate(group,project,sort);

但我仍然面临着像

这样的错误
'exception: FieldPath 'Longitude' doesn't start with $' on server localhost:27017. The full response is { "errmsg" : "exception: FieldPath 'Longitude' doesn't start with $", "code" : 16873, "ok" : 0.0 }

任何人都可以纠正或指出我的查询有什么问题,它会非常有帮助。 请帮忙.. 感谢

1 个答案:

答案 0 :(得分:0)

以下代码为我工作,

DBObject group = new BasicDBObject("$group",new BasicDBObject("_id","$IMEI Number")
    .append("Longitude", new BasicDBObject("$last","$Longitude"))
    .append("Latitude", new BasicDBObject("$last","$Latitude"))
    .append("Address", new BasicDBObject("$last","$Address"))
    .append("Timestamp", new BasicDBObject("$last","$Timestamp")));

    DBObject project = new BasicDBObject("$project", new BasicDBObject("IMEI Number","$_id")
    .append ("Longitude",1)
    .append ("Latitude",1)
    .append ("Address",1)
    .append ("Timestamp",1));

    DBObject sort = new BasicDBObject("$sort", new BasicDBObject("date",-1));

AggregationOutput output = dbCollection.aggregate(group,project,sort);