MongoDB:如何在Java中投影所有文档的单个内部字段?

huangapple go评论81阅读模式
英文:

MongoDB: How to project single inner field of all documents in Java?

问题

假设我有如下结构的文档集合:

{
    "_id" : 1,
    "name" : "user1",
    "age" : 25,
    "details": {
        "userType": 1
        ... 其他很多字段在这里
    }
}

我想要仅获取所有文档中的字段 "name" 和 "details.userType",使得结果如下:

[
    {
        "name": "user1",
        "details": {
            "userType": 1
        }
    },
    {
        "name": "user2",
        "details": {
            "userType": 1
        }
    }
    ... 等等
]

如何在 Java 中实现这一点呢?我不太清楚如何使用 Java 投影内部字段。

到目前为止,我能够使用以下代码投影出 name 字段:

Query query = new Query(Criteria.where("active").is(true));
query.fields().include("_id").include("name");
return template.find(query, BaseUser.class, collectionName);
英文:

Suppose I have collection of documents with structure below:

{
    "_id" : 1
    "name" : "user1",
    "age" : 25,
    "details": {
        "userType": 1
        ... many other fields here
    }
}

and I want to get all documents with fields "name" and "details.userType" only so I get result like this.

[
    {
        "name": "user1",
        "details": {
            "userType": 1
        }
    },
    {
        "name": "user2",
        "details": {
            "userType": 1
        }
    }
    ... etc
]

How can I achieve this using Java? I'm not sure how to project inner fields using java.

So far, I was able to project name field using this code

        Query query = new Query(Criteria.where("active").is(true));
        query.fields().include("_id").include("name");
        return template.find(query, BaseUser.class, collectionName);

答案1

得分: 1

由于您有嵌套对象,您可以简单地使用.include("details.userType")

英文:

Since you have nested object, simplay you can use .include("details.userType")

huangapple
  • 本文由 发表于 2020年8月27日 21:36:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/63617227.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定