如何在Spring Data MongoDB中使用Concatarray
我有以下JS代码:如何在Spring Data MongoDB中使用Concatarray,spring,mongodb,spring-data,spring-data-mongodb,Spring,Mongodb,Spring Data,Spring Data Mongodb,我有以下JS代码: $concatArrays: [ "$some.path", [ { "foo": "baz", "x": 5 } ] ] 我该如何使用它呢?玩具可以像下
$concatArrays: [
"$some.path",
[
{
"foo": "baz",
"x": 5
}
]
]
我该如何使用它呢?玩具可以像下面这样使用。您可以在
concat()
中传递聚合表达式或引用字段名。因此,您可以在concat()之前添加新数组
db.collection.aggregate([
{
$addFields: {
secondArray: [
{ "foo": "baz", "x": 5 }
]
}
},
{
"$project": {
combined: {
"$concatArrays": [ "$path", "$secondArray" ]
}
}
}
])
工作
假设数组字段在文档中定义如下:
{
"_id": ObjectId("60bdc6b228acee4a5a6e1736"),
"some" : {
"path" : [
{
"foo" : "bar",
"x" : 99
}
]
},
}
下面的Spring数据MongoDB代码返回结果
——一个包含两个元素的数组。数组字段“some.path”
和输入数组myArr
使用ArrayOperators.concatarray
API连接在一起
String json = "{ 'foo': 'baz', 'x': 5 }";
Document doc = Document.parse(json);
List<Document> myArr = Arrays.asList(doc);
MongoOperations mongoOps = new MongoTemplate(MongoClients.create(), "testDB");
Aggregation agg = newAggregation(
addFields()
.addFieldWithValue("myArr", myArr)
.build(),
addFields()
.addField("result").withValue(ConcatArrays.arrayOf("$some.path").concat("$myArr"))
.build()
);
AggregationResults<Document> results = mongoOps.aggregate(agg, "testColl", Document.class);
stringjson=“{'foo':'baz','x':5}”;
Document doc=Document.parse(json);
List myArr=Arrays.asList(doc);
MongoOperations mongoOps=新的MongoTemplate(mongoClient.create(),“testDB”);
聚合agg=newAggregation(
addFields()
.addFieldWithValue(“myArr”,myArr)
.build(),
addFields()
.addField(“result”).withValue(concatarray.arrayOf(“$some.path”).concat($myArr”))
.build()
);
AggregationResults=mongoOps.aggregate(agg,“testColl”,Document.class);
第二个数组是什么?它的字符串表示形式?你能用我提供的数组演示一下吗?你是否在$concatArray
中硬编码了foo
数组?我已经更新了answer@yaseco答案对你有帮助吗?
String json = "{ 'foo': 'baz', 'x': 5 }";
Document doc = Document.parse(json);
List<Document> myArr = Arrays.asList(doc);
MongoOperations mongoOps = new MongoTemplate(MongoClients.create(), "testDB");
Aggregation agg = newAggregation(
addFields()
.addFieldWithValue("myArr", myArr)
.build(),
addFields()
.addField("result").withValue(ConcatArrays.arrayOf("$some.path").concat("$myArr"))
.build()
);
AggregationResults<Document> results = mongoOps.aggregate(agg, "testColl", Document.class);