0

I have a Collection of objects :

db.coll.find().pretty();

{
    "_id" : "1",
    "elements" : [
        { "key" : "A", "value" : 10 },
        { "key" : "B", "value" : 1 },
    ]
}, 
{
    "_id" : "2",
    "elements" : [
        { "key" : "A", "value" : 1 },
        { "key" : "C", "value" : 33 },
    ]
}

I want to find the documents that contain an element with "key" equal to "A" AND its "value" is greater than 5.

Not sure if this is possible without using the aggregation framework.

2 Answers 2

1

Without aggregation, using $elemMatch and query will be as below :

db.coll.find({"elements":{"$elemMatch":{"$and":[{"key":"A"},{"value":{"$gt":5}}]}}}).pretty()

or if you want use aggregation then used following query for aggregation

db.coll.aggregate({"$unwind":"$elements"},{"$match":{"$and":[{"elements.key":"A"},{"elements.value":{"$gt":5}}]}}).pretty()
Sign up to request clarification or add additional context in comments.

Comments

1

Here is the query

db.coll.find({elements: {$elemMatch: {key: "A", value: {$gt: 5}}}});

It uses $elemMatch operator. The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria. (Refer the documentation)

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.