如何在 MongoDB 中移除不符合条件的元素?
mongodbdatabasebig data analytics更新于 2026/2/13 2:52:17
要移除元素,请使用 $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 } ] }

