簡體   English   中英

如何在 mongoDB 文檔中保留特殊密鑰並刪除其中的額外密鑰?

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

假設我有 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提供的 Projection

例如,包括使用org.springframework.data.mongodb.core.query.Queryorg.springframework.data.mongodb.core.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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM