Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb aggregate match array item with child array item

Tags:

mongodb

I would like to find documents that contains specific values in a child array.

This is an example document:

{
"_id" : ObjectId("52e9658e2a13df5be22cf7dc"),
"desc" : "Something somethingson",
"imageurl" : "http://",
"tags" : [ 
    {
        "y" : 29.3,
        "brand" : "52d2cecd0bd1bd844d000018",
        "brandname" : "Zara",
        "type" : "Bow Tie",
        "x" : 20,
        "color" : "52d50c19f8f8ca8448000001",
        "number" : 0,
        "season" : 0,
        "cloth" : "52d50d57f8f8ca8448000006"
    },
    {
        "y" : 29.3,
        "brand" : "52d2cecd0bd1bd844d000018",
        "brandname" : "Zara",
        "type" : "Bow Tie",
        "x" : 20,
        "color" : "52d50c19f8f8ca8448000001",
        "number" : 0,
        "season" : 0,
        "cloth" : "52d50d57f8f8ca8448000006"
    }
],
"user_id" : "52e953942a13df5be22cf7af",
"username" : "Thompson",
"created" : 1386710259971,
"occasion" : "ID",
"sex" : 0
}

The query I would like to do should look something like this:

db.posts.aggregate([
        {$match: {tags.color:"52d50c19f8f8ca8448000001", tags.brand:"52d2cecd0bd1bd844d000018", occasion: "ID"}},
        {$sort:{"created":-1}},
        {$skip:0},
        {$limit:10}
    ])

my problem is that I dont know how to match anything inside an array in the document like "tags". How can I do this?

like image 868
just_user Avatar asked Jul 25 '26 01:07

just_user


1 Answers

You could try to do it without aggregation framework:

db.posts.find(
{
    occasion: "ID", 
    tags: { $elemMatch: { color:"52d50c19f8f8ca8448000001", brand:"52d2cecd0bd1bd844d000018" } } 
}
).sort({created: -1}).limit(10)

And if you want to use aggregation:

db.posts.aggregate([
    {$match: 
        {
            tags: { $elemMatch: { color:"52d50c19f8f8ca8448000001", brand: "52d2cecd0bd1bd844d000018" } },
            occasion: "ID"
        }
    },
    {$sort:{"created":-1}},
    {$limit:10}
])
like image 131
Ivan.Srb Avatar answered Jul 28 '26 03:07

Ivan.Srb