开发者

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

开发者 https://www.devze.com 2023-03-10 22:41 出处:网络
I have a class called user which can be simplified to: class User { String[] friends; //Constructor etc...

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 (no开发者_JS百科t shown here), which I don't want.

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

++Cheers


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消