如何在Java中进行此查询

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


这是我正在做的代码

    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);


输出是

输出是

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


谢谢你的帮助

最佳答案

您需要将查询与要返回的字段分开。尝试更多类似这样的方法:

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);


还要注意,我删除了您在hsid。$ id之前的左花括号。

10-08 07:41