Home > Enterprise >  How to query MongoDB with specific request?
How to query MongoDB with specific request?

Time:01-13

Currently I have 3 blog posts saved in my database and I want to retrieve the blog post based on its name.

Here is my database in MongoDB:

[
  {
    _id: ObjectId("61de0e1562abb7ffd4089373"),
    name: 'learn-react',
    upvotes: 0,
    comments: []
  },
  {
    _id: ObjectId("61de0e1562abb7ffd4089374"),
    name: 'learn-node',
    upvotes: 0,
    comments: []
  },
  {
    _id: ObjectId("61de0e1562abb7ffd4089375"),
    name: 'my-thoughts-on-resumes',
    upvotes: 0,
    comments: []
  }
]

For instance, if I want to send a GET request to retrieve the 'learn-react' using the url: localhost:8000/articles/learn-react, how would I query the database? I only know how to retrieve all documents in the collection by using db.find() but how would i go about retrieving one particular blog post by its name in the url?

CodePudding user response:

Using $unwind you can deconstructs an array field. then using $match you can filter the documents ! Try this code it's help you !

db.getCollection('your collection').aggregate([  
  {
    $unwind: '$cource' //name of the array
  },
 {
    $match: { 'cource.name': 'learn-react' }
  },
]);
  •  Tags:  
  • Related