mongodb-常用命令

1.要从MongoDB中删除不在某个列表中的数据,您可以使用聚合管道的 `expr\` 操作符和 \`nin` 操作符

以下是一个示例,假设您有一个名为 `students` 的集合,其中包含一个 `name` 字段,您想要删除不在 `['Alice', 'Bob', 'Charlie']` 列表中的学生。

cs 复制代码
db.getCollection("semp_work_order_active").find({"orderCode" : { $in : ['DW-1311-20240525-9744150528000','DW-1311-20240522-8954433536000','DW-1311-20240522-9751815168000'] }}).limit(100000).skip(0)


db.getCollection("semp_work_order_active").remove( { _id: ObjectId("66513e3a491b0637bec40fa1") }, { justOne: true } )

在上面的示例中,`$$name` 是聚合管道中的变量,代表当前文档的 `name` 字段。`$nin` 操作符检查 `name` 是否不在 `['Alice', 'Bob', 'Charlie']` 列表中。

执行上面的命令后,所有不在 `['Alice', 'Bob', 'Charlie']` 列表中的学生将会被删除。

2.MongoDB中统计总数

db.semp_alarm_active.count()

3.mogodb删除数据

要从MongoDB中删除不在某个列表中的数据,您可以使用聚合管道的 $expr 操作符和 $nin 操作符。

以下是一个示例,假设您有一个名为 students 的集合,其中包含一个 name 字段,您想要删除不在 ['Alice', 'Bob', 'Charlie'] 列表中的学生。

复制代码
db.students.deleteMany(
  {
    $expr: { $nin: ['$$name', ['Alice', 'Bob', 'Charlie']] }
  }
)

在上面的示例中,$$name 是聚合管道中的变量,代表当前文档的 name 字段。$nin 操作符检查 name 是否不在 ['Alice', 'Bob', 'Charlie'] 列表中。

执行上面的命令后,所有不在 ['Alice', 'Bob', 'Charlie'] 列表中的学生将会被删除。

4.mongodb批量插入数据

在MongoDB中,批量插入数据可以通过以下几种方式实现:

  1. 使用`insertMany()`方法:

```javascript

const collection = db.get('myCollection');

const documents = [

{ name: 'John', age: 20 },

{ name: 'Jane', age: 25 },

{ name: 'Bob', age: 30 }

];

collection.insertMany(documents);

```

  1. 使用`bulkWrite()`方法:

```javascript

const collection = db.get('myCollection');

const operations = [

{ insertOne: { document: { name: 'John', age: 20 } } },

{ insertOne: { document: { name: 'Jane', age: 25 } } },

{ insertOne: { document: { name: 'Bob', age: 30 } } }

];

collection.bulkWrite(operations);

```

  1. 使用`forEach()`方法和`insertOne()`方法:

```javascript

const collection = db.get('myCollection');

const documents = [

{ name: 'John', age: 20 },

{ name: 'Jane', age: 25 },

{ name: 'Bob', age: 30 }

];

documents.forEach(document => collection.insertOne(document));

```

以上三种方法都可以实现批量插入数据,选择哪种方法取决于你的具体需求和喜好。

相关推荐
runepic2 分钟前
Python + PostgreSQL 批量图片分发脚本:分类、去重、断点续拷贝
服务器·数据库·python·postgresql
i***118617 分钟前
Django视图与URLs路由详解
数据库·django·sqlite
2***c43538 分钟前
Redis——使用 python 操作 redis 之从 hmse 迁移到 hset
数据库·redis·python
2***d88542 分钟前
redis的启动方式
数据库·redis·bootstrap
j***57681 小时前
【MySQL】mysqldump使用方法
数据库·mysql·oracle
Coder-coco1 小时前
在线商城系统|基于springboot vue在线商城系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·宠物
M***29911 小时前
MySQL:基础操作(增删查改)
数据库·mysql·oracle
2***c4351 小时前
Redis五种用途
数据库·redis·缓存
k***45991 小时前
MySQL----case的用法
android·数据库·mysql
San30.1 小时前
AIGC 时代如何优雅地操作数据库:SQLite + Python 实战与 SQL Prompt Engineering
数据库·sqlite·aigc