0

I am using mongodb and wanted to store my log data in the form array in the document. While reading from the collection I am using aggregation pipe line. When I tired to use the query in Mongo Booster, the Query is working fine but it was giving the following exception when I tried to use it by Java Program.

Details: --> db.version() - 3.2.7 --> mongo-java_driver: 3.2.2

Query in Mongo Booster:
=======================
db.logCollection.aggregate({$unwind:'$logList'},{ $sort : {'logList.log.timestamp': -1} },{ $match:{'logList.log.userId': "100100"}},{ $group: {_id: null, logList: {$push: '$logList'}}},{ $project: {  _id: 0,logList: {log:{timestamp: 1,operation:1}}}}).pretty()

 Query: using Java
 =================

 DBObject unwindField = new BasicDBObject("$unwind", "$logList");
  DBObject groupFields = new BasicDBObject("_id", null);         
  groupFields.put("logList", new BasicDBObject("$push","$logList")); 
  DBObject group = new BasicDBObject("$group", groupFields);
  DB logDB = mongoClient.getDB("logdb");
  DBCollection collection=logDB.getCollection(collectionName);      
  DBObject skipFields = new BasicDBObject("$skip",skip);
  DBObject limitFields = new BasicDBObject("$limit",limit);
  Iterable<DBObject> results =null;
  try { 
    results= collection.aggregate(unwindField, sortField,searchField,skipFields,limitFields,group,projectFields).results();
    } catch (Exception e) {
     log.error("readLogsFromCollection() Failed");

   }

Exception:
==========
com.mongodb.MongoCommandException: Command failed with error 16436: 'Unrecognized pipeline stage name: 'logList.log.timestamp' on server localhost:27017.
The full response is { "ok" : 0.0, "errmsg" : "Unrecognized pipeline stage name: 'logList.log.timestamp'", "code" : 16436 }

Input Document:
================

{
    "logList" : [
        {
            "log" : {
                "acctId" : "0",
                "info1" : {
                    "itemName" : "-",
                    "value" : "-"
                },
                "errorCode" : "",
                "internalInformation" : "",
                "kind" : "Infomation",
                "groupId" : "0",
                "logId" : "G1_1",
                "operation" : "startDiscovery",
                "result" : "normal",
                "userId" : "100100",
                "timestamp" : "1470980265729"
            }
        }
    ]
}

Could any body tell me what might be the problem, I read the issue is with version, but I Used mongo-java_driver-3.3 also but no use.

Thanks in advance.

7
  • Can you please add the query that works in mongodb shell that you are trying to code in java? Also, it will be useful if you can add sample document. Commented Sep 13, 2016 at 7:21
  • Hello @notionquest, Please look into updated query Commented Sep 13, 2016 at 8:57
  • Sample document please? Commented Sep 13, 2016 at 8:58
  • Sorry @notionquest, I dont have any document regarding this. Commented Sep 13, 2016 at 9:03
  • Do you mean you dont have a sample mongodb document to test this query? I didn't mean word document. Commented Sep 13, 2016 at 9:06

1 Answer 1

1

Here is the Java code for the below MongoDB query. I have used the same Java driver (mongo-java_driver: 3.2.2) as you mentioned in OP.

MongoDB Query:-

db.loglist.aggregate({$unwind:'$logList'},
{ $sort : {'logList.log.timestamp': -1} },
{ $match:{'logList.log.userId': "100100"}},
{ $group: {_id: null, logList: {$push: '$logList'}}},
{ $project: {  _id: 0,logList: {log:{timestamp: 1,operation:1}}}}).pretty();

Java Code:-

public static void main(String[] args) {
        MongoClient client = new MongoClient();
        MongoDatabase database = client.getDatabase("test");

        AggregateIterable<Document> mongoCollectionList = database.getCollection("loglist")
                .aggregate(Arrays.asList(Aggregates.unwind("$logList"), Aggregates.sort(Sorts.descending("logList.log.timestamp")),
                        Aggregates.match(Filters.eq("logList.log.userId", "100100")),
                        Aggregates.group("$id", Accumulators.push("logList", "$logList")),
                        Aggregates.project(Projections.include("logList.log.timestamp", "logList.log.operation"))
                        ));

        MongoCursor<Document> mongoCursor = mongoCollectionList.iterator();

        while (mongoCursor.hasNext()) {
            System.out.println(mongoCursor.next().toJson());

        }

    }

Output:-

{
    "_id": null,
    "logList": [{
        "log": {
            "operation": "startDiscovery",
            "timestamp": "1470980265729"
        }
    }]
}
Sign up to request clarification or add additional context in comments.

3 Comments

Hello @notionnquest, I am using depricated API. Can we make that is to work with the old API which I am using now
What is the reason for using the deprecated API?
It was there in all the places of code, for now I should continue with the same. It is working @notionquest, Since for match and sort there is no aggregation pipeline operator is missed in my java code, its not worked. Now its working.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.