3

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?

1 Answer 1

7

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}
])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.