简体   繁体   中英

$slice mongoDB Java

How can I make this query in Java

db.comments.find({ "hsID.$id" { "$oid" : "4fe71a50e7e9f22ae5fb96bf"}} , {commentList: { $slice : [ 2 , 2]}});

This the code I am doing

    BasicDBObject query = new BasicDBObject();
        BasicDBObject allFields = new BasicDBObject();
        ObjectId objectId = new ObjectId(objId);
        query.put("{hsID.$id", objectId);
        Integer[] sliceInt = { startIndex, pageSize };
        query.put( 
                "commentList",
                new BasicDBObject().append("$slice", sliceInt));
 DBCursor resultsCursor = CommentColl.find(allFields,query);

and the output is

And the output is

query  = { "{hsID.$id" : { "$oid" : "4fe71a50e7e9f22ae5fb96bf"} , "commentList" : { "$slice" : [ 2 , 2]}}

Thanks for your help

You need to separate the query from the fields you want returned. Try something more like this:

BasicDBObject query = new BasicDBObject("hsID.$id", new ObjectId(objId));
BasicDBObject fields = new BasicDBObject(
      "commentList",
       new BasicDBObject("$slice", new int[] { startIndex, pageSize }));
DBCursor resultsCursor = CommentColl.find(query, fields);

Notice also that I removed the opening curly brace that you had preceding hsid.$id.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM