假设我有具有如下文档的mongoDB集合
{
"_id" : ObjectId("5cb2dd4d378a8e2484e7bb69"),
"name":"ali",
"creator" : {
"name":"user1",
"code":2,
"type" : "desk",
"type_id" : "desk::bb36640a-e384-45ec-aafa-ce71b724c389"
},
"creatorPosition" : {
"name":"user2",
"role":"admin",
"type" : "position",
"type_id" : "position::9f711bb3-3aad-4936-b75a-4ddd024b4bb1"
},
"creatorDetails" : {
"name":"user1",
"type" : "deskUserAssignment",
"type_id" : "deskUserAssignment::dd46fa14-0fd3-43d7-8312-471bc253ee80"
}
}
我想保留每个字段中的两个键值("type", "type_id"
)并删除多余的键(例如"name", "code", "role"
)
我可以在一个mongo查询中处理吗?
此外,我想用Java编写此代码
最简单的方法是使用MongoTemplate提供的投影
例如排除字段:
Query query = new Query();
query.fields().include("creator.type").include("creator.type_id");
query.fields().include("creatorPosition.type").include("creatorPosition.type_id");
query.fields().include("creatorDetails.type").include("creatorDetails.type_id");
List<Document> documents = mongoTemplate.find(query, Document.class, "your_collection");
有关更多信息,请参见此文章:https://www.mkyong.com/mongodb/spring-data-mongodb-select-fields-to-return/