MongoDB find and remove - the fastest way

前端 未结 4 900
忘掉有多难
忘掉有多难 2021-02-07 13:56

I have a quick question, what is the fast way to grab and delete an object from a mongo collection. Here is the code, I have currently:

$cursor = $coll->find(         


        
相关标签:
4条回答
  • 2021-02-07 14:11

    Peter, It's hard to say what the best solution is here without understanding all the context - but one approach which you could use is findAndModify. This will query for a single document and return it, and also apply an update to it.

    You could use this to find a document to process and simultaneously modify a "status" field to mark it as being processed, so that other workers can recognize it as such and ignore it.

    There is an example here that may be useful: http://docs.mongodb.org/manual/reference/command/findAndModify/

    0 讨论(0)
  • 2021-02-07 14:16

    I make a new answer to remark the fact:

    As commented by @peterscodeproblems in the accepted answer. The native way to this in mongodb right now is to use the

    findAndModify(query=<document>, remove=True)
    

    As pointed out by the documentation.

    As it is native, and atomic, I expect this to be the faster way to do this.

    0 讨论(0)
  • 2021-02-07 14:28

    Use the findAndRemove function as documented here: http://api.mongodb.org/java/current/com/mongodb/DBCollection.html

    The findAndRemove function retrieve and object from the mongo database and delete it in a single (atomic) operation.

    findAndRemove(query, sort[, options], callback)

    • The query object is used to retrieve the object from the database (see collection.find())
    • The sort parameter is used to sort the results (in case many where found)
    0 讨论(0)
  • 2021-02-07 14:28

    I am new to mongodb and not entirely sure what your query is trying to do, but here is how I would do it

    # suppose database is staging
    # suppose collection is data
    use staging
    db.data.remove(<your_query_criteria>)
    

    where is a map and can contain any search criteria you want

    Not sure if this would help you.

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