简体   繁体   中英

Find and delete last entered entry from MongoDB collection

I added an element I need to delete it from my mongodb collection. It's the last entry I've entered. I've been following this link: How to delete the last item of a collection in mongodb . However, I'm not find to find the ID and I'm not able to extract this value from the Cursor (?). This is what I've done so far:

const db = client.db(databaseName);

let x = db
.collection("ford_twitter")
.find()
.sort({_id:-1});

The terminal log is:

在此处输入图像描述

If it's the last entry first check it's there using find . Once you find it, you can delete it.

I'll give you a complete example of how to achieve it:

async function find(){
try{
const call = await MongoClient.connect(uri, {
  useNewUrlParser: true,
  useUnifiedTopology: true
})
result = await call.db("todos")
                   .collection("quotes")
                   .find({})
                   .sort("_id", -1).limit(1)
                   .toArray()
console.log(result)                   
} catch(e){console.log(e)}
}
find()

In MongoDB, there are a couple of new objects like Cursor. To get the standard objects you need to read how to use the Cursor: it has properties and methods...

toArray() will give an array of that one element, that you can inspect.

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