如何在 Spring 数据 MongoDB 中使用 ConcatArrays
How to use ConcatArrays in Spring Data MongoDB
我有以下JS代码:
$concatArrays: [
"$some.path",
[
{
"foo": "baz",
"x": 5
}
]
]
如何对 ArrayOperators.ConcatArrays 执行相同的操作?
玩具可以像下面这样使用。您可以在 concat()
中传递聚合表达式或引用字段名称。所以你可以做的是,你可以在 concat()
之前添加新数组,比如
db.collection.aggregate([
{
$addFields: {
secondArray: [
{ "foo": "baz", "x": 5 }
]
}
},
{
"$project": {
combined: {
"$concatArrays": [ "$path", "$secondArray" ]
}
}
}
])
ArrayOperators.ConcatArrays concatArrays = ArrayOperators.ConcatArrays
.arrayOf("path")
.concat("secondArray");
假设文档中数组字段定义如下:
{
"_id": ObjectId("60bdc6b228acee4a5a6e1736"),
"some" : {
"path" : [
{
"foo" : "bar",
"x" : 99
}
]
},
}
以下 Spring 数据 MongoDB 代码 returns result
- 一个有两个元素的数组。使用 ArrayOperators.ConcatArrays
API.
连接数组字段 "some.path"
和输入数组 myArr
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);
我有以下JS代码:
$concatArrays: [
"$some.path",
[
{
"foo": "baz",
"x": 5
}
]
]
如何对 ArrayOperators.ConcatArrays 执行相同的操作?
玩具可以像下面这样使用。您可以在 concat()
中传递聚合表达式或引用字段名称。所以你可以做的是,你可以在 concat()
之前添加新数组,比如
db.collection.aggregate([
{
$addFields: {
secondArray: [
{ "foo": "baz", "x": 5 }
]
}
},
{
"$project": {
combined: {
"$concatArrays": [ "$path", "$secondArray" ]
}
}
}
])
ArrayOperators.ConcatArrays concatArrays = ArrayOperators.ConcatArrays
.arrayOf("path")
.concat("secondArray");
假设文档中数组字段定义如下:
{
"_id": ObjectId("60bdc6b228acee4a5a6e1736"),
"some" : {
"path" : [
{
"foo" : "bar",
"x" : 99
}
]
},
}
以下 Spring 数据 MongoDB 代码 returns result
- 一个有两个元素的数组。使用 ArrayOperators.ConcatArrays
API.
"some.path"
和输入数组 myArr
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);