MongoDB常用查询
MongoDB常用查询
软件:NoSQLBooster for MongoDB
SQL语句可以转成 MongoDB ,可以参考
例子:
db.tb_test_email.find({"mailNo":"20210709-154007-7132-59563"})
.projection({})
.sort({_id:-1})
.limit(100)
//1、查询所有记录
db.tb_test_email.find();
//2、查询去掉后的当前聚集集合中的某列的重复数据
db.tb_test_email.distinct("mailSubject");
//3、查询投产待办通知的记录
db.tb_test_email.find({"mailSubject":"投产待办通知"});
//4、大于:$gt;小于:$lt;大于等于:$gte;小于等于:$lte;
db.tb_test_email.find({"needSendNum":{$lt: 100}});
//5、模糊查询%投产待办通知%
db.tb_test_email.find({mailSubject:/投产待办通知/})
//6、以投产开头的
db.tb_test_email.find({mailSubject:/^投产/})
//7、搜索id、mailNo
db.tb_test_email.find({},{id:1,mailNo:1})
//8、搜索id、mailNo,条件是needSendNum>100
db.tb_test_email.find({needSendNum:{$gt:100}},{id:1,mailNo:1})
//9、按照id排序 1 升序 -1 降序
db.tb_test_email.find().sort({id:-1});
//10、两个条件,注意单引号
db.tb_test_email.find({mailNo:'20210707-145435-6208-14288',mailSubject:'投产待办通知'})
//11、查询前 5 条数据
db.tb_test_email.find().limit(5)
//12、查询 10 条以后的数据
db.tb_test_email.find().skip(10)
//13、查询在 5-10 之间的数据
db.tb_test_email.find().limit(10).skip(5)
//14、or 查询
db.tb_test_email.find({$or: [{needSendNum:102},{needSendNum:2}]})
//15、findOne 查询第一条数据
db.tb_test_email.findOne()
//16.查询数量大于100的数量
db.tb_test_email.find({needSendNum:{$gt: 100}}).count()
//17.id查询
db.tb_test_email.find({"_id":ObjectId('641d4b858bbd58678278ebd6')})
.projection({})
.sort({ _id: -1 })
.limit(100)
//18.更新时间查询
db.tb_test_email.aggregate([{
$match: {
updateDate : {
$gte: 1678723200000,
$lte:1679298301806
}
}
}, {
$sort: {
_id: -1
}}
])
//19.自动化推送统计聚合查询
db.tb_test_email.aggregate([{
$match: {
title: "自动化测试-0227-02"
}
},
{
$project: {
_id:0,
assignId: 1,
level:1,
receiveUserId:1,
receiveUserAccount:1,
receiveUserName:1,
appTuid:1,
title:1,
content:1,
customParameters:1,
messageType:1,
failSendCount:1,
sendState:1,
sendDesc:1,
createBy:1,
updateBy:1,
createDate:{ $dateToString: {format:"%Y-%m-%d %H:%M:%S",timezone:"Asia/Shanghai",date:{$toDate: "$createDate"} } },
updateDate:{ $dateToString: {format:"%Y-%m-%d %H:%M:%S",timezone:"Asia/Shanghai",date:{$toDate: "$updateDate"} } }
}
}, {
$sort: {
createDate: -1
}
}
])
//20.批量造任务
for (var i = 0; i < 11; i++) {
db.getCollection("tb_test_email").insert({
"assignId": "63f5abbefa74c57f8d011ab3",
"receiveUserId": "local\\111",
"receiveUserAccount": "1111",
"receiveUserName": "系统管理员",
"appTuid": "20230210-151329-8759-19227",
"title": "测试批量任务-"+i,
"content": "测试批量任务-"+i,
"customParameters": "{\"111\":\"222\"}",
"messageType": NumberInt(2),
"sendTime": NumberLong("1677044671089"),
"failSendCount": NumberInt(0),
"sendState": NumberInt(1),
"sendDesc": "待发送",
"msgId": "9f81cfe3-23eb-40e8-9d57-810e70da60ea",
"systemId": "20200917-094756-9152-57789",
"systemCode": "DRE",
"instanceId": "20200917-094956-9635-58544",
"createBy": "rabbitmq",
"createDate": NumberLong("1677044671090"),
"updateBy": "rabbitmq",
"updateDate": NumberLong("1677044734876"),
"_class": "org.saic.dre.repository.message.model.device.AssignDeviceMessageEntity"
})
}