如何在 MongoDB 中删除不满足条件的元素?
要删除元素,请使用 $pull,对于这样的条件,请使用 $ne。MongoDB 中的 $ne 用于选择字段值不等于指定值的文件。
让我们创建一个包含文件的集合 -
> db.demo410.insertOne(
... {
... details: [{isMarried:false}, {isMarried:true}, {isMarried:false}, {isMarried:"Chris"}]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e70efc515dc524f70227681")
}使用 find() 方法显示集合中的所有文件 -
> db.demo410.find();
这将产生以下输出 -
{ "_id" : ObjectId("5e70efc515dc524f70227681"), "details" : [ { "isMarried" : false }, { "isMarried" : true }, { "isMarried" : false }, { "isMarried" : "Chris" } ] }以下是在 MongoDB 中删除不满足条件的元素的查询 -
> db.demo410.updateMany(
... { "details": { "$elemMatch": { "isMarried": { "$ne": true } } } },
... { "$pull": { "details": { "isMarried": { "$ne": true } } } }
... )
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }使用 find() 方法显示集合中的所有文件 -
> db.demo410.find();
这将产生以下输出 -
{ "_id" : ObjectId("5e70efc515dc524f70227681"), "details" : [ { "isMarried" : true } ] }
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP