Remove only one document in MongoDB

后端 未结 9 2026
日久生厌
日久生厌 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-12 23:50

    You need to perform two separate queries for this

    • take only one item from the matching filters

      var item = db.collection.findOne({'condition':'some condition'})
      
    • and delete the item by using the id

       db.collection.remove({_id: item._id});
      
    0 讨论(0)
  • 2021-01-12 23:52

    Can't you just run a find first to get the id then a delete when you have the one you want?

    0 讨论(0)
  • 2021-01-12 23:55

    db.collection.remove now has a justOne flag

    http://docs.mongodb.org/manual/reference/method/db.collection.remove/#db.collection.remove

    0 讨论(0)
  • 2021-01-12 23:57

    If there are multiple records and you want to delete only first record, then set justOne parameter in remove() method.

    Here, you want to delete only 1. Thus, set "justOne" parameter as 1.

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

    0 讨论(0)
  • 2021-01-12 23:58

    To remove one document from collection use the bellow command

    db.collectionname.remove({"_id": ObjectId("5473293d43ecdre56352457f3a")})

    0 讨论(0)
  • 2021-01-12 23:58

    Try this one for delete.

    db.users.deleteOne({"_id": ObjectId("5473293d43ecdre56352457f3a")});
    
    0 讨论(0)
提交回复
热议问题