简体   繁体   中英

how to keep special keys in filed of mongoDB documents and remove extra keys in there?

suppose that I have mongoDB collection that has documents like below

{
    "_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"
    }
}

I want to keep two key values ( "type", "type_id" ) from each fields and remove extra keys (such as "name", "code", "role" )

Can I handle this in one mongo query?

In addition, I want to write this code in java

The simplest way to do is using Projection that MongoTemplate offers

For example including fields using org.springframework.data.mongodb.core.query.Query and org.springframework.data.mongodb.core.MongoTemplate for retrieving the results:

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");

For more information see this Article: https://www.mkyong.com/mongodb/spring-data-mongodb-select-fields-to-return/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM