您的位置:首页 > 数据库 > Mongodb

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

2016-11-30 10:00 609 查看
原文

Projections

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

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

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


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

Inclusion

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

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

include("quantity")


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

include("quantity", "totalAmount")


Exclusion

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

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

exclude("quantity")


这个例子包含了
quantity
totalAmount
字段:

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
方法.

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

fields(include("quantity", "totalAmonut"), excludeId())
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息