Reputation: 265
So I have a product document which has a nested images document. The structure is like this:
{
"_id" : ObjectId("551e617eccfff2fc193c9869"),
"currency" : "US DOllar",
"images" : [
{
"filename" : "551e617eccfff2fc193c9869_logo-big.jpg",
"height" : NumberLong(500),
"width" : NumberLong(500),
"updated_at" : ISODate("2015-04-07T10:35:10.142Z"),
"created_at" : ISODate("2015-04-03T09:53:31.168Z"),
"_id" : ObjectId("551e631bccfff278173c9869"),
"deleted_at" : ISODate("2015-04-03T09:53:43.102Z")
},
{
"filename" : "551e617eccfff2fc193c9869_sameer.jpg",
"height" : NumberLong(500),
"width" : NumberLong(500),
"updated_at" : ISODate("2015-04-03T10:00:39.969Z"),
"created_at" : ISODate("2015-04-03T10:00:39.969Z"),
"_id" : ObjectId("551e64c7ccfff200173c9869")
}
],
"is_active" : "1",
"updated_at" : ISODate("2015-04-07T08:05:15.932Z"),
"created_at" : ISODate("2015-04-03T09:46:38.340Z"),
}
Now I want only one sub document, i.e. image whose filename
is "551e617eccfff2fc193c9869_logo-big.jpg" along with the whole document.
How can I do that?
So i got the answer to do it in mongo .. now how can i do that in laravel with jessenger/mongo-db package..
Upvotes: 1
Views: 738
Reputation: 7840
For finding this you should use following query.
db.collectionName.find({"images.filename":"551e617eccfff2fc193c9869_logo-big.jpg"},{"images.$.filename":1,"currency":1}).pretty()
Upvotes: 1
Reputation: 103425
Use $elemMatch
projection operator
db.product.find(
{"images.filename": "551e617eccfff2fc193c9869_logo-big.jpg"},
{
"images": {
"$elemMatch": {"filename": "551e617eccfff2fc193c9869_logo-big.jpg"}
},
"currency": 1, "is_active": 1, "updated_at": 1, "created_at": 1
}
)
Alternatively you can also use the $ projection
operator:
db.product.find(
{"images.filename": "551e617eccfff2fc193c9869_logo-big.jpg"},
{
"images.$": 1, "currency": 1, "is_active": 1, "updated_at": 1, "created_at": 1
}
)
Upvotes: 2