您可以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" }