我有一个在后端生成的查询,在这个项目中,路径是基于根元素构建的。
{
data: [
{
$project: {
'Source.Code': {
$ifNull: [
'$Source.Code',
'$$REMOVE'
]
},
'Source.Description': {
$ifNull: [
'$Source.Description',
'$$REMOVE'
]
},
'Source._id': {
$ifNull: [
'$Source._id',
'$$REMOVE'
]
}
}
}
]
}
上面是投影,如您所见,源是基于Source
文档中的字段创建的。我的问题是,就像我在子字段中所做的那样,我想检查Source
上的Source
,如果根本没有文档,就删除它。有点像
{
'Source': {
$ifNull: [
'$Source',
'$$REMOVE'
]
}
我不知道如何在聚合中构建这样的查询。在这里,Source是一个对象,它有多个字段,我希望在Source
上检查null,如果它不是null,那么检查它的所有字段,并相应地添加到Source
中。
{
Source: {
Code: "Code",
Description: "test",
_id: "SomeID"
}
}
如果描述为空,那么
{
Source: {
Code: "Code",
_id: "SomeID"
}
}
编辑1:
现在,我想添加一个例子,其中我有一个对象源,它有可以被翻译的字段。我所说的可译的意思是,它们是i18n字段,其中包含语言字段。因此,请考虑下面的示例
{
Source: {
Code: "Code",
Description: {
"en":"test",
"fr": "testfr",
"def": "test"
},
_id: "SomeID"
}
}
所以从我之前的查询来看
{
data: [
{
$project: {
'Source.Code': {
$ifNull: [
'$Source.Code',
'$$REMOVE'
]
},
'Source.Description': {
$ifNull: [
'$Source.Description.en',
'$$REMOVE'
]
},
'Source._id': {
$ifNull: [
'$Source._id',
'$$REMOVE'
]
}
}
}
]
}
因此,Source.Description.en会将.en附加到路径中,以便从描述中获取en。如何更改此边缘情况的查询?
发布于 2021-06-14 05:53:26
$objectToArray
将Source
对象转换为数组键值格式$filter
不是空的。$arrayToObject
将键值转换回对象。$addFields
从desscription
获取en
$cond
来检查它的空对象,然后删除,否则返回db.collection.aggregate([
{
$project: {
Source: {
$arrayToObject: {
$filter: {
input: { $objectToArray: "$Source" },
cond: { $ne: ["$$this.v", null] }
}
}
}
}
},
{ $addFields: { "Source.Description": "$Source.Description.en" } },
{
$project: {
Source: {
$cond: [{ $eq: ["$Source", {}] }, "$$REMOVE", "$Source"]
}
}
}
])
https://stackoverflow.com/questions/67971308
复制相似问题