Mongo java driver - retrieve slice of array without any other field

ぐ巨炮叔叔 提交于 2019-12-08 03:10:30

问题


I have a class called user which can be simplified to:

class User {
    String[] friends;
    //Constructor etc...
}

It is stored in a mongo collections called users. I am trying to retrieve the first N elements of the friends array without anything else from the class.

Right now, I tried using the following java query:

db.getCollection("users").find(new BasicDBObject(), new BasicDBObject("friends", new BasicDBObject("$slice", N))).next();

As expected, I get a User object with the friends array slice. But it also returns all the other fields in the User class (not shown here), which I don't want.

Any idea how I can force it to send back only the friends array?

++Cheers


回答1:


Try adding "friends: true" like this:

db.getCollection("users").find(new BasicDBObject(), new BasicDBObject("friends", new BasicDBObject("$slice", N)).append("friends", true)).next();

It should have the _id and the friends fields.



来源:https://stackoverflow.com/questions/6272546/mongo-java-driver-retrieve-slice-of-array-without-any-other-field

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