【问题标题】:How to access array elements in mongodb如何访问mongodb中的数组元素
【发布时间】:2021-10-06 17:15:03
【问题描述】:

你好,我是 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"),
    "user_id" : "xyz",
    "from_time" : 13.0,
    "to_time" : 14.0,
    "status" : false
}

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

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

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

/* 6 */
{
    "_id" : ObjectId("60f27483f6d12949670676e9"),
    "user_id" : "abc",
    "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
    }

请有人回答如何实现这一目标

【问题讨论】:

  • 您的数据如何?你能添加一个输入示例吗?
  • 感谢您的回复,我得到了答案,但我在这里提供我的数据,以防它帮助任何其他人,我的问题中现在给出的数据

标签: mongodb mongoose aggregation-framework


【解决方案1】:

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

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

【讨论】:

  • 但是,请注意对象索引位置和 0、空值等
  • 感谢您的回答解决了我的问题
猜你喜欢
  • 1970-01-01
  • 2020-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-25
  • 2013-04-06
  • 1970-01-01
相关资源
最近更新 更多