Remove by _id in MongoDB console

前端 未结 11 1172
野的像风
野的像风 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 17:05

    Do you have multiple mongodb nodes in a replica set?

    I found (I am using via Robomongo gui mongo shell, I guess same applies in other cases) that the correct remove syntax, i.e.

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

    ...does not work unless you are connected to the primary node of the replica set.

    0 讨论(0)
  • 2020-12-22 17:06

    Well, the _id is an object in your example, so you just need to pass an object

    'db.test_users.remove({"_id": { "$oid" : "4d513345cc9374271b02ec6c" }})'
    

    This should work

    Edit: Added trailing paren to ensure that it compiled.

    0 讨论(0)
  • 2020-12-22 17:09

    first get the ObjectID function from the mongodb ObjectId = require(mongodb).ObjectID;

    then you can call the _id with the delete function

    "_id" : ObjectId("4d5192665777000000005490")

    0 讨论(0)
  • 2020-12-22 17:13

    Solution and Example:

    1- C:\MongoDB\Server\3.2\bin>mongo (do not issue command yet because you are not connected to any database yet, you are only connected to database server mongodb).

    2-

    show dbs analytics_database 0.000GB local 0.000GB test_database 0.000GB

    3-

    use test_database switched to db test_database

    4-

    db.Collection.remove({"_id": ObjectId("5694a3590f6d451c1500002e")}, 1); WriteResult({ "nRemoved" : 1 })

    now you see WriteResult({ "nRemoved" : 1 }) is 1 not 0.

    Done.

    0 讨论(0)
  • 2020-12-22 17:15

    Suppose we have this dummy collection:

    { "_id" : ObjectId("5ea53fedaa79db20d4e14284"), "item" : "planner", "qty" : 75 }
    

    simply use:

    db.inventory.deleteOne({ _id: ObjectId("5ea53fedaa79db20d4e14284") })
    

    it will be deleted with this as a response:

    { "acknowledged" : true, "deletedCount" : 1 }
    

    Thats it.

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