如何使用父文档展平动态字段 - Spring Data Mongo DB [英] How to Flatten dynamic field with parent document - Spring data Mongo DB
问题描述
在我的 Spring boot 项目中有一个像这样的文档:
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.
我使用 MongoRepository 来存储这个值:
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?
我是 Spring Data mongodb 的新手,因为我们最近从 Oracle 跳到了 mongo.
I'm new to spring data mongodb as we have recently made the jump to mongo from Oracle.
推荐答案
如果您使用的是最新的 mongo 版本,那么您可以使用 $replaceRoot 和 $mergeObjects(参考自 stackoverflow 答案)
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)
这篇关于如何使用父文档展平动态字段 - Spring Data Mongo DB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!