我正在使用mongob mongodb并试图在我的回调中重现这种格式,如下所示:
var logSchema = new Schema({
application_name: String,
file_name: String,
type: String,
created_at: Date,
log_identifier: String,
environment: String
});
这是我的模特:
LogModel.aggregate([
{
"$unwind": "$type"
}, {
$group: {
"_id": {
type: "$type"
},
"Warning": {
"$push": {
"$cond": {
if: {
$eq: ["$type", "Warning"]
},
then: {
"_id": "$_id",
"application_name": "$application_name",
"created_at": "$created_at",
"log_identifier": "$log_identifier",
"enviroment": "$enviroment"
},
else: false,
}
}
},
"Error": {
"$push": {
"$cond": {
if: {
$eq: ["$type", "Error"]
},
then: {
"_id": "$_id",
"application_name": "$application_name",
"created_at": "$created_at",
"log_identifier": "$log_identifier",
"enviroment": "$enviroment"
},
else: false,
}
}
}
}
}
], function (err, logs) {
if (err) reject(err);
else resolve(logs)
});
我正在使用聚合方法按类型设置类型和分组,如下所示:
[
{
"_id": {
"type": "Error"
},
"Warning": [
false
],
"Error": [
{
"_id": "5a8dd312c681334d558e6169",
"application_name": "teste",
"created_at": "2018-02-02T23:55:06.000Z",
"log_identifier": "1"
}
]
},
{
"_id": {
"type": "Warning"
},
"Warning": [
{
"_id": "5a7b6a36a5799090cf76bc4c",
"application_name": "teste",
"created_at": "2018-02-02T23:37:06.000Z",
"log_identifier": "1"
},
{
"_id": "5a7b6a49a5799090cf76bc4d",
"application_name": "teste",
"created_at": "2018-02-02T23:55:06.000Z",
"log_identifier": "1"
},
{
"_id": "5a8dcdbcadb65b484e888091",
"application_name": "teste",
"created_at": "2018-02-02T23:55:06.000Z",
"log_identifier": "1"
}
],
"Error": [
false,
false,
false
]
}
]
但我的结果是
{{1}}
我不希望字段带有错误值,我不知道其他方法来重现我想要的东西。
任何人都可以帮助我吗?
答案 0 :(得分:1)
您可以在3.4版本中重写您的聚合,如下所示。
按类型 $group
并推送每种类型的值。使用$replaceRoot
$arrayToObject
输出指定的密钥。
LogModel.aggregate([
{"$group":{
"_id":"$type",
"data":{
"$push":{
"_id":"$_id",
"application_name":"$application_name",
"created_at":"$created_at",
"log_identifier":"$log_identifier",
"enviroment":"$enviroment"
}
}
}},
{"$replaceRoot":{
"newRoot":{
"$let":{
"vars":{"array":[["$_id","$data"]]},
"in":{"$arrayToObject":"$$array"}}
}
}}
])