这是我的样本数据库集合:
{
"_id" : ObjectId("5a9797b480591678e0771190"),
"staff_id" : NumberInt(172),
"temp_name" : "Regular Employment",
"individual_setting" : false,
"employment_category" : "Regular Employee",
"branch_office" : "Cebu Branch Office",
"availability_status" : "Incumbent",
"req_working_hours" : "08:00",
"fixed_brk_time_from" : "12:00",
"fixed_brk_time_to" : "13:00",
"sch_time_setting" : [
{
"holiday" : [
"Saturday",
"Friday"
],
"biweekly_odd" : [
],
"biweekly_even" : [
"Saturday"
],
"clock_in_mon" : "08:40",
"clock_in_tue" : "08:40",
"clock_in_wed" : "08:40",
"clock_in_thu" : "08:40",
"clock_in_fri" : "08:40",
"clock_in_sat" : "08:40",
"clock_in_sun" : null,
"clock_in_hol" : null,
"clock_out_mon" : "18:00",
"clock_out_tue" : "18:00",
"clock_out_wed" : "18:00",
"clock_out_thu" : "18:00",
"clock_out_fri" : "18:00",
"clock_out_sat" : "18:00",
"clock_out_sun" : null,
"clock_out_hol" : null,
"_id" : ObjectId("5a9797b480591678e077118f")
}
],
"date_to_start" : ISODate("2018-03-01T06:03:32.050+0000"),
"createdAt" : ISODate("2018-03-01T06:03:32.066+0000"),
"updatedAt" : ISODate("2018-03-01T06:03:32.066+0000"),
"__v" : NumberInt(0)
}
在clock_in_mon
字段下的字段clock_in_hol
和sch_time_setting
之间,我想要计算有多少字段有数据或不为空。由于每个员工都有不同的time_setting,因此这些字段可能在其他员工中的数据很少。
对此的预期计数是:6,因为只有clock_in_mon
到clock_in_sat
才有数据。
我从这里尝试了Count fields in a MongoDB Collection的代码,但我不能在我的情况下做到。
尝试以下聚合:
db.yourCollectionName.aggregate([
{
$project: {
totalClockIns: {
$map: {
input: "$sch_time_setting",
as: "setting",
in: {
_id: "$$setting._id",
kvPairs: {
$objectToArray: "$$setting"
}
}
}
}
}
},
{
$project: {
totalClockIns: {
$map: {
input: "$totalClockIns",
as: "clockIn",
in: {
_id: "$$clockIn._id",
count: {
$size: { $filter: { input: "$$clockIn.kvPairs", as: "pair", cond: { $and: [
{$eq: [{ $indexOfBytes: [ "$$pair.k", "clock_in_" ] },0]},{$ne: ["$$pair.v",null]}] } } } }
}
}
}
}
}
])
要分析文档,您需要比较键名称。要做到这一点,你必须使用$objectToArray运算符,它将变换和对象转换为键值对列表。然后你可以找到那些key
名称以clock_
开头的对(使用$indexOfBytes),其中值不等于null
。使用$filter你可以摆脱所有其他对,你需要做的就是使用$size来获得数组的长度。
这将给你以下结果:
{ "_id" : ObjectId("5a9797b480591678e0771190"), "totalClockIns" : [ { "_id" : ObjectId("5a9797b480591678e077118f"), "count" : 12 } ] }