mongodb 层次较深的查询写法

本文介绍两种查询特定日期(如2012年3月30日)登录用户信息的方法,包括使用$elemMatch进行精确匹配及$where结合JavaScript实现灵活查询。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

{
    "_id": ObjectId("4f7524f23e38831a887ecf02"),
    "info": {
        "name": "小强",
        "gender": "男",
        "login_log": {
            "0": {
                "ip": "127.0.0.1",
                "time": "20120301"
            },
            "1": {
                "ip": "172.16.26.16",
                "time": "20120330"
            }
        }
    }
}
{
    "_id": ObjectId("4f7524f23e38831a887ecf02"),
    "info": {
        "name": "小明",
        "gender": "女",
        "login_log": {
            "0": {
                "ip": "127.0.0.1",
                "time": "20120328"
            },
            "1": {
                "ip": "172.16.26.16",
                "time": "20120329"
            }
        }
    }
}

查询在2012-03-30登录的用户信息,查询条件如下:

//方法1
$cursor = $db->find(
    array('info.login_log'=>array('$elemMatch'=>array('time'=>'20120330'))),
    array('info.name'=>true)  //'info.name'是指要查询的字段,参数可以为空
);

foreach($cursor as $doc){ print_r($doc);}
//方法2
$js = "
function (){ 
    var status = false; 
    for(var i in this.info.login_log){ 
        if(this.info.login_log[i].time == '20120330'){
            status = true;
        }
    }
    return status;
}";

$cursor = $db->find(array('$where'=>$js),array('info.name'=>true));
foreach($cursor as $doc){ print_r($doc);}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值