英文:
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")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论