Retrieve subDocument on Moloquent

37 views Asked by At

I have this document

{
    _id: ObjectId('5f8970f19e6afb628a2edd07'),
    name: 'pack 1',
    price: 100,
    min_price: 100,
    updated_at: ISODate('2020-10-16T10:07:45.570Z'),
    created_at: ISODate('2020-10-16T10:07:45.530Z'),
    available_quantity: -1,
    quantity: -1,
    slots: [
        {
            duration: '365',
            price: 100,
            _id: '5f8970f19e6afb628a2edd07_5f8970f18b3aa',
            created_at: ISODate('2020-10-16T10:07:45.529Z'),
            updated_at: ISODate('2020-10-16T10:07:45.529Z'),
            available_quantity: -1,
            quantity: -1
        },
        {
            duration: '255',
            _id: '5f8970f19e6afb628a2edd07_5f8970f18b3c7',
            created_at: ISODate('2020-10-16T10:07:45.529Z'),
            updated_at: ISODate('2020-10-16T10:07:45.529Z'),
            price: 100,
            available_quantity: -1,
            quantity: -1
        }
    ]
}

and i would like only this subdocument using Moloquent

{
            duration: '365',
            price: 100,
            _id: '5f8970f19e6afb628a2edd07_5f8970f18b3aa',
            created_at: ISODate('2020-10-16T10:07:45.529Z'),
            updated_at: ISODate('2020-10-16T10:07:45.529Z'),
            available_quantity: -1,
            quantity: -1
        }

The search must be done by _id on subDocument eg. _id: 5f8970f19e6afb628a2edd07_5f8970f18b3aa

1

There are 1 answers

0
wak786 On

Here is the mongo query.

db.collection.aggregate([
  {
    "$unwind": "$slots"
  },
  {
    "$match": {
      "slots._id": "5f8970f19e6afb628a2edd07_5f8970f18b3aa"
    }
  },
  {
    "$project": {
      _id: 0,
      price: "$slots.price",
      duration: "$slots.duration",
      created_at: "$slots.created_at",
      updated_at: "$slots.updated_at",
      _id: "$slots._id",
      available_quantity: "$slots.available_quantity",
      quantity: "$slots.quantity"
    }
  }
])

Also created a Mongo playground here.

https://mongoplayground.net/p/-Vmv3_I2RyM