如何在 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 } ] }

更新于: 03-04-2020

352 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.