查询
2025/5/13大约 2 分钟mongodb数据库
查询
// 条件过滤查询,字段1和字段2同时满足
db.col.find({field1: "field1Value", field2: "field2Value"})
// 或逻辑怎么查
db.col.find({
$or: [{field1: "1"}, {field2: "2"}]
})
// 不等于怎么查
db.col.find({status: {$exists: true, $ne: "active"}})
// 不在多个值里怎么查
db.users.find({status: {$nin: ["active", "pending"]}})
// 时间范围怎么查
db.col.find({
creation_time: {$gt: ISODate("2024-12-31T23:59:59.999Z")}
});
// 限制返回条数
db.col.find({field: "fieldValue"}).limit(1)
// 常见类似json格式化打印,一个字段一行
db.col.find({field: "fieldValue"}).limit(1).pretty()
// 自定义格式化打印
db.col.find({field: "fieldValue"}).limit(1).forEach(doc => {
print(`${doc.field1},${doc.createtime.toISOString()},${doc.deadline.toISOString()},${doc.field2}`)
})
// 定义通用的转义函数:处理换行、回车、制表符等特殊字符
function escapeSpecialChars(str) {
if (str === null || str === undefined) {
return ""; // 处理字段为空的情况
}
// 先转为字符串,再替换:\n→\\n,\r→\\r,\t→\\t(按需扩展)
return String(str)
.replace(/\n/g, "\\n")
.replace(/\r/g, "\\r")
.replace(/\t/g, "\\t");
}
db.online_standard_history.find({
opt: "add",
record_time: {$gt: ISODate("2024-12-31T23:59:59.999Z")}
}).forEach(doc => {
const category = escapeSpecialChars(doc.category);
const task = escapeSpecialChars(doc.task);
const standard_content = escapeSpecialChars(doc.standard_content);
print(`${doc.qa_id},${doc.record_time.toISOString()},${category},${task},${standard_content}`)
})
// 查询文档字段的数据类型
db.col.find().limit(1).forEach(doc => {
print(typeof doc.createtime);
})
// 字段A存在且不为null
db.col.find({"A": {$ne: null, $exists: true}})
// 字段A不存在或值为null
db.col.find({$or: [{"A": {$exists: false}}, {"A": null}]})字段是数组怎么查
两种场景:
- 字段本身是数组类型(只要这个字段的值是数组,不管里面内容)
// arrField 这个字段的值是数组
db.coll.find({ arrField: { $type: "array" } })MongoDB 4.4 $type 也可以用数字 4:
{$type: 4}
db.coll.find({ arrField: { $type: 4 } })- 数组里面包含某个元素(最常用)
// 数组里包含 10
db.coll.find({ arrField: 10 })
// 等价于 $in
db.coll.find({ arrField: { $in: [10] } })- 数组同时包含多个元素(全部都要有)$all
// 数组里同时有 10 和 20
db.coll.find({ arrField: { $all: [10, 20] } })- 数组长度匹配 $size
// 数组长度等于3
db.coll.find({ arrField: { $size: 3 } })- 数组内元素满足条件(至少一个匹配)$elemMatch
// 数组里对象,至少一个对象满足 age>18
db.coll.find({
arrField: {
$elemMatch: { age: { $gt: 18 } }
}
})- 数组内元素严格等于匹配
// ✅ 匹配字段值严格等于 [1,2](顺序也要一致)
db.coll.find({ arrField: { $eq: [1,2] } })聚合查询
// 根据集合中字段分组
db.col.aggregate([
{
$group: {
_id: "$xx_id", // xx_id 是字段名,按xx_id分组
avg_worktime: {$avg: "$worktime"} // worktime 是字段名,计算每组的平均值
}
}
])
// 聚合时,先匹配文档再分组
db.col.aggregate([
{
$match: {
status: {$in: ["pass", "not_pass"]}
}
},
{
$group: {
_id: "$xx_id",
avg_worktime: {$avg: "$worktime"},
count: {$sum: 1} // 可选:添加计数显示每个分组有多少文档
}
}
])
// 也可以先筛选数据,再聚合分组
db.col.find({status: {$in: ["pass", "not_pass"]}}).aggregate([
{
$group: {
_id: "$xx_id",
avg_worktime: {$avg: "$worktime"},
count: {$sum: 1} // 可选:添加计数显示每个分组有多少文档
}
}
])