mongoose多条件模糊查询使用

本文介绍了在mongoose中如何进行多条件模糊查询,特别是在Hosts文档中,同时对hostIp和localIp字段进行模糊匹配,并结合非模糊查询的categoryTag和hostType字段。通过示例展示了使用$or和$regex实现复杂查询的接口测试结果。

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

多条件模糊查询
查询条件:

在这里插入图片描述
需要在Hosts文档中同时模糊查询字段hostIp与字段localIp并且组合条件查询出categoryTag字段与hostType字段,categoryTag字段与hostType字段查询未非模糊查询(上图状态条件先不作为条件查询)

const where = {
    $or:[{ hostIp: new RegExp(47) }, { localIp: new RegExp(47) }],
    categoryTag: '主机A',
    hostType: '1',
}
await this.ctx.model.Hosts.find(where)

通过postman测试接口可得:

{
    "success": true,
    "payload": {
        "list": [
            {
                "customHostGroups": [],
                "_id": "5d2dd2a4c5b5c21ae00fcfec",
                "tenantId": "2ba56b7c3f8c49598207d2a9fe54970b",
                "hostIp": "22.106.182.777",
                "localIp": "47.18.231.33",
                "sshPort": 22,
                "sshUsername": "root",
                "sshConnectionType": 0,
                "sshPassword": "abcd123123",
                "hostType": 1,
                "accessWay": 0,
                "isAllocated": false,
                "isAllocatedToEnv": false,
                "projectId": null,
                "projectName": null,
                "envId": null,
                "envName": null,
                "dr": 0,
                "_created_at": "2019-07-16T13:35:32.308Z",
                "_updated_at": "2019-07-16T13:35:32.308Z",
                "categoryTag": "主机A"
            }
        ],
        "page": 2,
        "size": 1,
        "total": 1,
        "totalPage": 1
    }
}

模糊查询主要是mongoose的RegExp的使用,配合$or则为多条件模糊查询

$or 用于多条件查询 http://www.nodeclass.com/api/mongoose.html#query_Query-or

$regex 用于模糊查询 http://www.nodeclass.com/api/mongoose.html#query_Query-regex

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值