Projections-Java下MongoDB查询限制返回字段

来源:互联网 发布:社交网络的好处和坏处 编辑:程序博客网 时间:2024/05/20 15:36

原文

Projections

Projections 类为所有的MongoDB projection操作提供了静态工厂方法. 每个方法都返回Bson类型的一个实例, 可以传递到任何一个需要Projection的方法.

简便起见, 你可以选择静态地导入所有Projections的方法:

import static com.mongodb.client.model.Projections.*;

下面所有的例子都假设你已经静态导入.

Inclusion

默认, 每个文档的所有字段都被包含, 为了指定要包含一个或多个字段(默认不包含除了_id之外的所有字段), 使用include方法.

这个例子包含了quantity字段和(隐式的)_id字段:

include("quantity")

这个例子包含了quantitytotalAmount字段以及(隐式的)_id字段:

include("quantity", "totalAmount")

Exclusion

为了指定不包含一个或多个字段(默认包含所有字段), 使用exclude方法.

这个例子不包含’quantity字段:

exclude("quantity")

这个例子包含了quantitytotalAmount字段:

exclude("quantity", "TotalAmount")

Exclusion of _id

为了明确排除_id字段, 使用excludeId方法:

excludeId()

下面方法的简写:

exclude("_id")

Array Element Match with a Supplied Filter

为了指定一个包含只满足提供的查询过滤条件数组的第一个元素的投射(elemMatch操作), 使用elemMatch操作符, 它需要一个字段名称和一个过滤器.

这个例子投射orders数字的quantity字段大于3的第一个结果:

elemMatch("orders", Filters.gt("quantity", 3))

Array Element Match with an Implicit Filter

为了指定一个包含满足查询提供的过滤器的第一个元素的投射(positional $ operator), 使用只需要一个参数的elemMatch方法.

这个例子投射满足查询过滤器的order数组的第一个元素:

elemMatch("orders")

Slice

为了查询a slice of an array(数组切片), 使用slice方法.
这个例子投射tag数组的前7个元素:

slice("tags", 7)

这个例子跳过数组tags的前2个元素, 投射接下来的5个元素:

slice("tags", 2, 5)

Text Score

我MongoDB还没懂这么多, 所以还不知道这个是什么…
为了指定the score of a $text query的投射, 使用metaTextScore方法来指定投射字段.

下面这个例子投射text score 作为score字段的值

metaTextScore("score")

Combining Projections

要组合多个投射, 使用fields方法.

这个例子包含了quantitytotalAmount字段, 不包含_id字段:

fields(include("quantity", "totalAmonut"), excludeId())
0 0
原创粉丝点击