$slice mongoDB Java

泪湿孤枕 提交于 2019-12-13 04:52:23

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/12545851/slice-mongodb-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!