英文:
How to repeat all fields key and set the new value in $project stage in aggregate mongodb?
问题
我有一个模式模型,其中有许多字段,就像下面的示例一样,我想将suggest_foo
中的根字段克隆到聚合的$project阶段,而不必手动重写这些字段,然后根据我的逻辑设置这些字段的新值。
示例:
- 模式模型:
const fooSchema = new Schema({
suggest_foo: {
foo1: String,
foo2: String,
foo3: String,
foo4: String,
foo5: String,
}
// ...
})
- 种子数据:
{
suggest_foo: {
foo1: 'Foo1',
foo2: 'Foo2',
foo3: 'Foo3',
foo4: 'Foo4',
foo5: 'Foo5',
}
}
- 聚合查询代码:
fooSchema.aggregate([
// ...
{
$project: {
// 我想要克隆suggest_foo中的根字段(例如:foo1、foo2、foo(n))到这里。
}
}
])
我期望的输出结果如下:
{
foo1: 'Foo1 maybe you like',
foo2: 'Foo2 maybe you like',
foo3: 'Foo3 maybe you like',
foo4: 'Foo4 maybe you like',
foo5: 'Foo5 maybe you like',
}
英文:
I have a schema model with so many fields like below example, I want to clone root field in suggest_foo
to $project stage of aggregation without having to manually rewrite those fields and then set those fields with new value as my logic.
Example:
-
schema model:
const fooSchema = new Schema({ suggest_foo: foo1: String, foo2: String, foo3: String, foo4: String, foo5: String, } ... })
-
seeds data:
{ suggest_foo: { foo1: 'Foo1', foo2: 'Foo2', foo3: 'Foo3', foo4: 'Foo4', foo5: 'Foo5', } }
-
aggregate query code:
fooSchema.aggregate([ ... { $project: { // I want to clone root in suggest_foo (eg: foo1, foo2, foo(n)...) to be here. } } ])
My output result that I expected look like:
{
foo1: 'Foo1 maybe you like',
foo2: 'Foo2 maybe you like',
foo3: 'Foo3 maybe you like',
foo4: 'Foo4 maybe you like',
foo5: 'Foo5 maybe you like',
}
答案1
得分: 1
一种选择是使用$replaceRoot
与$arrayToObject
和$objectToArray
,因为这将允许您在循环中操作数组:
db.collection.aggregate([
{$replaceRoot: {
newRoot: {
$arrayToObject: {
$map: {
input: {$objectToArray: "$suggest_foo"},
in: {
v: {$concat: ["$$this.v", "也许你会喜欢"]},
k: "$$this.k"
}
}
}
}
}}
])
在播放示例上查看它是如何工作的。
英文:
One option is to use $replaceRoot
with $arrayToObject
and $objectToArray
as this will allow you to manipulate array in a loop:
db.collection.aggregate([
{$replaceRoot: {
newRoot: {
$arrayToObject: {
$map: {
input: {$objectToArray: "$suggest_foo"},
in: {
v: {$concat: ["$$this.v", " maybe you like"]},
k: "$$this.k"
}
}
}
}
}}
])
See how it works on the playground example
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论