1

can somebody tell me please how to find items in Mongodb array which contains more than 2 items with specific value? For example if I have two documents like this:

{
    someArray: [
        {'aaa' => 1},
        {'aaa' => 1}
    ]
}
{
    someArray: [
        {'aaa' => 1},
        {'aaa' => 2}
    ]
}

I need to find the first document which contains two items which 'aaa' value is 1. I dont mean $elemMatch I need to count the number of the matched items. Thanks for any help.

2
  • Could you show sample output Commented May 24, 2019 at 17:12
  • I dont understand. Output should be the document. For my purpose _id will be enough. Commented May 24, 2019 at 17:14

2 Answers 2

1

You can use below aggregation:

db.col.aggregate([
    {
        $match: {
            $expr: {
                $gte: [
                    { $size: { $filter: { input: "$someArray", cond: { $eq: [ "$$this.aaa", 1 ] } } } },
                    2
                ]
            }
        }
    },
    {
        $limit: 1
    }
])

$filter allows you to apply your condition, then you can use $size to get the length of filtered array and compare it againts your value using $gte

Sign up to request clarification or add additional context in comments.

Comments

0

You can use $indexOfArray to find whether the array contains that element and then compare with the $size of the array using $eq

db.collection.find({
  "$expr": {
    "$and": [
      { "$ne": [{ "$indexOfArray": ["$someArray.aaa", 1] }, -1] },
      { "$eq": [{ "$size": "$someArray" }, 2] }
    ]
  }
}).limit(1)

MongoPlayground

2 Comments

It's all about interpretation here, and what actually means "two items which 'aaa' value is 1", in this case any of them has to have aaa set to 1, I'm not sure if that's the point
:-):-):-) Yes. Even I am confused now. I thought may be any of the element contains value 1. But I think you are right both elements should contain the 1. Let's see what OP needs. Most probably you are right.

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.