Remove only one document in MongoDB

后端 未结 9 2027
日久生厌
日久生厌 2021-01-12 23:42

when I call

db.collection.remove({\'condition\':\'some condition\'});

This one line will delete all the matching condition documents.

相关标签:
9条回答
  • 2021-01-13 00:10

    I used this and it's worked for me

    db.eventList.remove({"_id":ObjectId("5d9f3bd0c02cef7d50bb97fb")});
    

    this is working on MongoDB shell version: 3.2.17

    here eventList ===> collection

    0 讨论(0)
  • 2021-01-13 00:13

    According to MongoDB db.collection.remove() reference:

    justOne

    An optional boolean value. To limit the deletion to just one document, set to true. Omit to use the default value of false and delete all documents matching the deletion criteria.

    You can set the justOne to true, in order to do it.

    Before MongoDB version 2.6:

    db.collection.remove(
       <query>,
       <justOne>
    )
    

    MongoDB version 2.6 or later:

    db.collection.remove(
       <query>,
       {
         justOne: <boolean>,
         writeConcern: <document>
       }
    )
    

    Like this: db.collection.remove({"condition": "some condition"}, {justOne: true});.

    0 讨论(0)
  • 2021-01-13 00:14

    For example the name of the db is 'abc' and under that there's a collection by name 'users' and users has an email which is 'test@test.com' which you want to remove: 1. On the terminal if you type 'show dbs' (without quotation' ') it would list all the databases including 'abc' 2. If you type 'use abc', it would switch to your desired db - abc (with the message: "switched to db abc") 3. Now if you type 'show collections', it would show all the collections including 'users' 4. If you want to list all the documents in this collection, you simply type: db.users.find({}) 5. If you want to delete a specific document in this collection, type: db.users.remove({"email":"test@test.com"})

    If it's successful, it would display - WriteResult({ "nRemoved" : 1 })

    0 讨论(0)
提交回复
热议问题