This is my document, where user register and create their store and in each store user can add books now anonymous user want to fetch the book by id or all the books available in system
[
{
_id: ObjectId("61c0a1a895a761d0fe1a1408"),
storeName: 'Rose Book Store',
ownerName: 'Rose Ahmed',
books: [
{
name: 'economics',
totalStock: 12,
stockStatus: true,
_id: ObjectId("61c20d9fcfef88e51e37bdaa")
}
],
createdAt: ISODate("2021-12-21T17:02:30.221Z"),
__v: 0
},
{
_id: ObjectId("61c17c1481adc44ea10c6083"),
storeName: 'Toufik Book Store',
ownerName: 'Toufik Ahmed',
books: [
{
name: 'Database',
totalStock: 14,
stockStatus: true,
_id: ObjectId("61c217b72e2dc3395071bb26")
},
{
name: 'Database',
totalStock: 14,
stockStatus: true,
_id: ObjectId("61c217e92e2dc3395071bb2b")
},
{
name: 'MySql',
totalStock: 0,
stockStatus: false,
_id: ObjectId("61c218142e2dc3395071bb31")
}
],
createdAt: ISODate("2021-12-21T18:03:13.296Z"),
__v: 0
}
]
how can i get all books, expected output
books:[{
name:"Some_book",
totalStock:12,
stockStatus: true,
_id: "Some_id"
},
{
name:"Some_other_book"
totalStock:0,
stockStatus:false
_id: "Some_id"
}]
how can i get book by id when user enters any valid book _id expected output in given below
books:{
name:"some_book",
totalStock: 2,
_id: "some object_id"}
CodePudding user response:
Here i am sharing normal aggregation query https://mongoplayground.net/p/SOO_Ffia5-q
where we are just grouping all books into one document so you get all the books.
Same aggregation can be used to get the matching book based on id. https://mongoplayground.net/p/ILHMW-kPueD
in aggregation we used below stages:
match: filter book based on _id of book unwind: unwind matched document as matched document may have other nonmatched booked in same user/store match: filter unwinded books so we just get matched book project: to just return book and not all fields
Using this sample queries you can easily create your mongoose equivalent code,