0

I have a collection with two documents:

{
    "type":"s",
    "disp":[
        {
            "quantity":1,
            "date":20141109
        },
        {
            "quantity":1,
            "date":20141110
        }
    ]
},
{
    "type":"d",
    "disp":[
        {
            "quantity":1,
            "date":20141109
        },
        {
            "quantity":0,
            "date":20141110
        }
    ]
}

I have to make a query (with one or more dates) to retrieve a document where all the given dates have a quantity greater than 0.

So if I search for a date 20141109 then I have to retrieve both but searching for 20141110 or both dates 20141109 and 20141110 should return only type "s" as it's the only with a quantity bigger than 0 for every dates used as parameters

P.S. sorry for my English, it's not my first language

1 Answer 1

2

To do such a match for one date, use $elemMatch:

db.test.find({ "disp" : { "$elemMatch" : { "quantity" : { "$gt" : 0 }, "date" : 20141109} } })

For multiple dates you will need to combine queries like the above using $and:

db.test.find({ "$and" : [
    { "disp" : { "$elemMatch" : { "quantity" : { "$gt" : 0 }, "date" : 20141109 } } },
    { "disp" : { "$elemMatch" : { "quantity" : { "$gt" : 0 }, "date" : 20141110 } } }
] })
Sign up to request clarification or add additional context in comments.

1 Comment

I just wonder if there's a way to get only the "disp" elements matched

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.