在 MongoDB 中删除部分数据?
您可以为此使用 map()。我们首先创建一个带有文档的集合:
> db.deleteDemo.insertOne({"Name":"John"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd550492cba06f46efe9f06") } > db.deleteDemo.insertOne({"Name":"Carol"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd5504d2cba06f46efe9f07") } > db.deleteDemo.insertOne({"Name":"Sam"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd550512cba06f46efe9f08") } > db.deleteDemo.insertOne({"Name":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd5505d2cba06f46efe9f09") } > db.deleteDemo.insertOne({"Name":"Robert"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd550682cba06f46efe9f0a") } > db.deleteDemo.insertOne({"Name":"Chris"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd5506f2cba06f46efe9f0b") } > db.deleteDemo.insertOne({"Name":"Mike"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd550752cba06f46efe9f0c") } > db.deleteDemo.insertOne({"Name":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd5507a2cba06f46efe9f0d") } > db.deleteDemo.insertOne({"Name":"James"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd550822cba06f46efe9f0e") } > db.deleteDemo.insertOne({"Name":"Jace"}); { "acknowledged" : true, "insertedId" : ObjectId("5cd550862cba06f46efe9f0f") }
以下查询用来展示有关集合的所有文档,通过 find() 方法:
> db.deleteDemo.find();
由此将产生以下输出:
{ "_id" : ObjectId("5cd550492cba06f46efe9f06"), "Name" : "John" } { "_id" : ObjectId("5cd5504d2cba06f46efe9f07"), "Name" : "Carol" } { "_id" : ObjectId("5cd550512cba06f46efe9f08"), "Name" : "Sam" } { "_id" : ObjectId("5cd5505d2cba06f46efe9f09"), "Name" : "David" } { "_id" : ObjectId("5cd550682cba06f46efe9f0a"), "Name" : "Robert" } { "_id" : ObjectId("5cd5506f2cba06f46efe9f0b"), "Name" : "Chris" } { "_id" : ObjectId("5cd550752cba06f46efe9f0c"), "Name" : "Mike" } { "_id" : ObjectId("5cd5507a2cba06f46efe9f0d"), "Name" : "Bob" } { "_id" : ObjectId("5cd550822cba06f46efe9f0e"), "Name" : "James" } { "_id" : ObjectId("5cd550862cba06f46efe9f0f"), "Name" : "Jace" }
以下查询用于在 MongoDB 中删除部分数据:
> var value = db.deleteDemo.find({}, {_id : 1}).skip(5).toArray().map(function(documentValue) { return documentValue._id; }); > db.deleteDemo.remove({_id: {$in:value}}); WriteResult({ "nRemoved" : 5 })
以上查询将在第 5 条记录后删除所有文档。让我们显示以上集合中的所有文档:
> db.deleteDemo.find();
由此将产生以下输出:
{ "_id" : ObjectId("5cd550492cba06f46efe9f06"), "Name" : "John" } { "_id" : ObjectId("5cd5504d2cba06f46efe9f07"), "Name" : "Carol" } { "_id" : ObjectId("5cd550512cba06f46efe9f08"), "Name" : "Sam" } { "_id" : ObjectId("5cd5505d2cba06f46efe9f09"), "Name" : "David" } { "_id" : ObjectId("5cd550682cba06f46efe9f0a"), "Name" : "Robert" }
广告