Home > OS >  How to find one document in MongoDB by unique slug from Next.js?
How to find one document in MongoDB by unique slug from Next.js?

Time:09-11

My MongoDB data looks like this:

[
  {
    "Post": "this is a post",
    "_id": ObjectId("630f3c32c1a580642a9ff4a0"),
    "slug": "this-is-a-title",
    "title": "This is a title"
  },
  {
    "Post": "this is a post",
    "_id": ObjectId("630f3c32c1a580642a9ff4a1"),
    "slug": "this-is-a-title-b",
    "title": "This is a title B"
  }
]

All slug are unique, how can I find one document by that unique slug?

I am not using Mongoose.

CodePudding user response:

you can use the find method...

the query works like this, in the find method you need to specify the property that you want to compare (in this case "slug") and the you can use the $eq (equal to) operator with your value.

 db.YOURCOLLECTION.find({
            slug: {
                $eq: 'this-is-a-title'
            },
        })

here the playground with a working example based on your data:

https://mongoplayground.net/p/X_1MAuhKBS4

official docs https://www.mongodb.com/docs/manual/reference/operator/query/eq/

  • Related