Skip to main content

MongoDB杂项记录

常用基本命令

# 帮助
help
# 当前数据库
db
# 查看函数的信息
db.getName
# 调用函数
db.getName()
# 查看函数的文档
db.getName.help()
# 切换数据库
use [dbname]
# 给当前数据库添加用户
db.addUser()
# 写入数据
db.[tableName].insertOne({name: "小明"})
# 查询数据
db.[tableName].findOne()
# 查看所有数据库
show dbs
# 查看所有集合
show collections

创建用户

db.createUser({user:"lmkscrm", pwd:"lmkscrm", roles:[{role:"dbOwner", db: "lmkscrm"}]})
db.createUser({user:"root", pwd:"root", roles:[{role:"root", db:"admin"}]})

聚合查询

分组求和

db.getCollection(
  'lmk_store_contacts_task_stat_202404'
).aggregate(
  [
    {
      $match: {
        shopid: 154,
        userid: { $in: ['HaoRenYiShengPingAn'] },
        date: { $lte: '2024-04-11' }
      }
    },
    {
      $group: {
        _id: '$userid',
        total: { $sum: '$num' }
      }
    }
  ],
  { maxTimeMS: 60000, allowDiskUse: true }
);

时间戳格式化

db.getCollection(
'lmk_market_task_execute_time_20240506'
).aggregate(
[
{
$match: {
subtask_id: '202405051641449192136'
}
},
{
$project: {
status: '$status',
ct: {
$dateToString: {
format: '%Y-%m-%d %H:%M:%S',
date: {
$toDate: {
$multiply: ['$created_at', 1000]
}
},
timezone: '+08:00'
}
}
}
}
],
{ maxTimeMS: 60000, allowDiskUse: true }
);