简体   繁体   中英

How do I delete a field from a MongoDB collection by key?

I have a MongoDB database with a settings collection that I need to delete a field from by key. In the docs I see that deleteOne accepts an Object [key, value].

How can I delete it with just the key since the value is unknown?

// key - req.params.key
db.collection('settings').deleteOne(???);

If I understand you question correctly. You want to delete a document where a particular field exists?

If so you can use the $exists element query operator.

Let's say the field name is config .

db.collection('settings').deleteOne({config: {$exists: true}})

Here is the source documentation: https://docs.mongodb.com/manual/reference/operator/query/exists/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM