本文介绍了Mongo Java驱动程序-检索没有任何其他字段的数组切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为user的类,可以简化为:

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

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

它存储在称为用户的mongo集合中.我正在尝试从类中检索friends数组的前N个元素,而没有其他任何内容.

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.

现在,我尝试使用以下Java查询:

Right now, I tried using the following java query:

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

正如预期的那样,我得到了一个带有friends数组切片的User对象.但是它还会返回User类中的所有其他字段(此处未显示),这是我不想要的.

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?

++欢呼声

推荐答案

尝试添加"friends:true",像这样:

Try adding "friends: true" like this:

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

它应该具有_id和friends字段.

It should have the _id and the friends fields.

这篇关于Mongo Java驱动程序-检索没有任何其他字段的数组切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 12:44