Remove by _id in MongoDB console

前端 未结 11 1170
野的像风
野的像风 2020-12-22 16:14

In the MongoDB console how can I remove a record by id? Here\'s my collection :

[ 
  {
     \"_id\" : { \"$oid\" : \"4d512b45cc9374271b02ec4f\" },
     \"nam         


        
相关标签:
11条回答
  • 2020-12-22 16:53
    db.collection("collection_name").deleteOne({_id:ObjectID("4d513345cc9374271b02ec6c")})
    
    0 讨论(0)
  • 2020-12-22 16:54

    Very close. This will work:

    db.test_users.deleteOne( {"_id": ObjectId("4d512b45cc9374271b02ec4f")});
    

    i.e. you don't need a new for the ObjectId.

    Also, note that in some drivers/tools, remove() is now deprecated and deleteOne or deleteMany should be used instead.

    0 讨论(0)
  • 2020-12-22 16:55

    Even though this post is outdated, collection.remove is deprecated! collection.delete_one should be used instead!

    More information can be found here under #remove

    0 讨论(0)
  • 2020-12-22 16:56

    The answer is that the web console/shell at mongodb.org behaves differently and not as I expected it to. An installed version at home worked perfectly without problem ie; the auto generated _id on the web shell was saved like this :

    "_id" : { "$oid" : "4d512b45cc9374271b02ec4f" },
    

    The same document setup at home and the auto generated _id was saved like this :

    "_id" : ObjectId("4d5192665777000000005490")
    

    Queries worked against the latter without problem.

    0 讨论(0)
  • 2020-12-22 16:59

    I've just bumped into this myself and this variation worked for me:

    db.foo.remove({**_id**: new ObjectId("4f872685a64eed5a980ca536")})
    
    0 讨论(0)
  • 2020-12-22 17:05

    If you would like to remove by a list of IDs this works great.

    db.CollectionName.remove({
        "_id": {
            $in: [
                ObjectId("0930292929292929292929"),
                ObjectId("0920292929292929292929")
            ]
         }
    }) 
    
    0 讨论(0)
提交回复
热议问题