How to Flatten dynamic field with parent document - Spring data Mongo DB

巧了我就是萌 提交于 2021-02-08 08:26:22

问题


In my Spring boot project have a Document like so:

@Document(collection="AuditTable")
public class AuditTable {

    @Id
    private String id;

    private Map<String, String> properties;

where properties is a dynamic field i.e. it can take in as many different key-value pairs.

I use MongoRepository to store this value:

@Repository
public interface AuditTableRepo extends MongoRepository<AuditTable, String> {
}

Now when I store it in the Collection it looks like this:

whereas I want it to look like this:

"_id": "XYZ" 
"_class": "XYZ" 
"workCaseId":"12" 
"taskName":"AUDIT" 
"owner":"ANSHU" 
"createdDate":"XYZ"

Any idea about how I can fix this without using converters? Or if I do have to use them how should I do it?

I'm new to spring data mongodb as we have recently made the jump to mongo from Oracle.


回答1:


If you are using the latest mongo version then you can use $replaceRoot and $mergeObjects (reference from stackoverflow answer)

let pipeline = [
    {
        "$replaceRoot":{
            "newRoot":{
                "$mergeObjects":[
                    {
                        "id":"$id"
                    },
                    "$properties"
                ]
            }
        }
    }
]
db.collection.aggregate(pipeline)


来源:https://stackoverflow.com/questions/54950724/how-to-flatten-dynamic-field-with-parent-document-spring-data-mongo-db

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!