如何访问mongodb中的数组元素

你好,我是 mongodb 语法的新手 我使用查询获得了以下结果

   {
    "_id" : "abc","info" : [ 
        {
            "user_status" : true,"timeactive" : 2.0
        },{
            "user_status" : false,"timeactive" : 1.0
        }
    ]
}

数据库中的数据如下

/* 1 */
{
    "_id" : ObjectId("60f25f41f6d12949670676e4"),"user_id" : "xyz","from_time" : 12.0,"to_time" : 13.0,"status" : true
}

/* 2 */
{
    "_id" : ObjectId("60f25f41f6d12949670676e5"),"from_time" : 13.0,"to_time" : 14.0,"status" : false
}

/* 3 */
{
    "_id" : ObjectId("60f25f41f6d12949670676e6"),"from_time" : 14.0,"to_time" : 15.0,"status" : true
}

/* 4 */
{
    "_id" : ObjectId("60f25f41f6d12949670676e7"),"from_time" : 15.0,"to_time" : 17.0,"status" : false
}

/* 5 */
{
    "_id" : ObjectId("60f27483f6d12949670676e8"),"user_id" : "abc","status" : true
}

/* 6 */
{
    "_id" : ObjectId("60f27483f6d12949670676e9"),"from_time" : 17.0,"to_time" : 18.0,"status" : false
}

我使用的查询

db.users.aggregate(
[
    {$match:{ status_to_time : {$ne:null} }},{$set:{totalTime:   {$subtract:["$status_to_time","$status_from_time"]} }},{$group:{_id:{user_id:"$information_id",user_status:"$status"},allSum:{$sum:"$totalTime"} }},{$project:{"user_id":"$_id.user_id","user_status":"$_id.user_status",timeA:"$allSum",_id:0}},{$sort:{user_id:1,user_status:-1}},{$group:{_id:"$user_id",info:{$push:{user_status:"$user_status",timeactive:"$timeA"}} }},]
    )

但我也想在参数 timeDiv 中实现划分为 info[0].timeactive / info[1].timeactive 所以我的最终查询结果应该是

    {
        "_id" : "abc","info" : [ 
            {
                "user_status" : true,"timeactive" : 2.0
            },{
                "user_status" : false,"timeactive" : 1.0
            }
        ]
timeDiv:2 // division as info[0].timeactive / info[1].timeactive
    }

请有人回答如何实现这一点

as516344224 回答:如何访问mongodb中的数组元素

您可以像这样使用 $addField、$divide 和 $arrayElemAt: playground.

只需在查询的末尾添加此聚合,您就会得到预期的结果。

本文链接:https://www.f2er.com/5002.html

大家都在问