collection.findOneAndDelete()¶

MongoDB Logo
ServerDriversCloudToolsGuides
Get MongoDB
Close ×
MongoDB Stitch

Introduction
Tutorials
Users & Authentication
MongoDB Atlas
    Overview
    Configure MongoDB
        Link a MongoDB Atlas Cluster
        Define Roles and Permissions
        Filter Incoming Queries
        Enforce a Document Schema
        Configure Advanced Rules
        Specify Cluster Read Preference
        Enable Wire Protocol Connections
    Work With MongoDB
        Add Data to MongoDB
        Find Documents in MongoDB
        Update Documents in MongoDB
        Delete Documents from MongoDB
        Watch for Document Changes
        Run Aggregation Pipelines
        Connect Over the Wire Protocol
    Reference
        MongoDB Actions
            mongodb.db()
            database.collection()
            collection.find()
            collection.findOne()
            collection.findOneAndUpdate()
            collection.findOneAndReplace()
            collection.findOneAndDelete()
            collection.insertOne()
            collection.insertMany()
            collection.updateOne()
            collection.updateMany()
            collection.deleteOne()
            collection.deleteMany()
            collection.aggregate()
            collection.count()
        Query Roles
        Query Filters
        Document Schemas
        Connection Strings
        Service Limitations
        CRUD & Aggregation APIs
GraphQL
MongoDB Mobile
Functions
Triggers
External Services
Values & Secrets
Application Deployment
Hosting
Troubleshooting
Stitch Administration
Application Logs
Client SDKs
Release Notes

Stitch > MongoDB Atlas > Reference > MongoDB Actions 

collection.findOneAndDelete()

On this page

Definition
Usage
    Example
    Parameters
    Return Value

Definition¶

collection.findOneAndDelete()

Remove a single document from a collection based on a query filter and return a document with the same form as the document immediately before it was deleted. Unlike collection.deleteOne(), this action allows you to atomically find and delete a document with the same command. This avoids the risk of other update operations changing the document between separate find and delete operations.
Usage
Example

Functions JavaScript SDK Android SDK iOS SDK 

To call the collection.findOneAndDelete() action from a Function, get a collection handle with database.collection() then call the handle’s findOneAndUpdate() method.

// Find the first document that has a quantity greater than 25
const query = { “quantity”: { “$gte”: 25 } };
// Sort the documents in order of descending quantity before
// deleting the first one.
const options = {
“sort”: { “quantity”: -1 }
}

return itemsCollection.findOneAndDelete(query, options)
.then(deletedDocument => {
if(deletedDocument) {
console.log(Successfully deleted document that had the form: ${deletedDocument}.)
} else {
console.log(“No document matches the provided query.”)
}
return deletedDocument
})
.catch(err => console.error(Failed to find and delete document: ${err}))

Parameters

Functions JavaScript SDK Android SDK iOS SDK 

The collection.findOneAndDelete() action has the following form:

findOneAndDelete(query, options)

Parameter Description

Query Filter
query:

Required. A standard MongoDB query document that specifies which document to delete. You can use most query selectors except for evaluation, geospatial, or bitwise selectors.

If multiple documents match the query, only the first document in sort order or natural order will be updated.

Delete Options
options:

A document that specifies configuration options for the query. The options document has the following form:

{
“sort”: ,
“projection”:
}

Sort
options.sort:

Optional. Specifies the query sort order. Sort documents specify one or more fields to sort on where the value of each field indicates whether MongoDB should sort it in ascending (1) or descending (0) order. The sort order determines which document collection.findOneAndReplace() affects.

Example

The following sort document specifies that documents should be sorted first by age from highest to lowest. Once sorted by age, the result set should further be sorted by name in alphabetical order for each distinct age value.

{ age: 0, name: 1 }

Projection
options.projection:

Optional. A document that specifies which fields MongoDB should return or withhold in each document that matches the query.

To return all fields in the matching documents, omit this parameter or specify an empty projection document ({}).

To return specific fields and the document’s _id, specify the fields in the projection document with a value of 1:

// Includes the field in returned documents
{ : 1 }

To withhold specific fields, specify the fields in the projection document with a value of 0:

// Withholds the field from returned documents
{ : 0 }

Note

You may specify either fields to include or fields to withhold but not both. For example, the following projection is invalid because it simultaneously includes the name field and withholds the address field:

// Invalid
// Can’t simultaneously include and withhold
{ “name”: 1, “address”: 0 }

The exception to this rule is the _id field, which you may withhold from any query:

// Valid
// Can exclude _id while including other fields
{ “_id”: 0, “name”: 1 }

Return Value

Functions JavaScript SDK Android SDK iOS SDK 

The collection.findOneAndDelete() action returns a :mdn:`Promise

<Web/JavaScript/Reference/Global_Objects/Promise>` that resolves to a single document that the query deleted. If no documents match the specified query, the promise resolves to null.

Promise<document|null>

← collection.findOneAndReplace() collection.insertOne() →

© MongoDB, Inc 2008-present. MongoDB, Mongo, and the leaf logo are registered trademarks of MongoDB, Inc.
Was this page helpful?
Yes
No

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值