Y
Y
Yuriyant2016-02-17 21:48:57
MongoDB
Yuriyant, 2016-02-17 21:48:57

Mongodb and subdocument search?

Let's say we have a collection document like this:

{
       "objects": [
         {
           "a": 1,
           "prop":2,
         },
         {
           "a": 2,
           "prop":3
         } 
        ] 
}

There is a task to find the documents having subdocuments with identical properties. Let's say you need to find a document that contains two nested documents with the property a == 1
I built a condition:
{
     	"objects": { "$elemMatch": { "$and": [ {"a":1}, { "a":1} ]} }
}

This query, as expected, will return me a document where there are any nested documents with the property a: 1 and a = 2, etc. And here's how to make a query so that it returns me only those documents where there are two nested documents with properties a=1 and there must be as many of them as the conditions we have written.
Ideally, you should only return documents of this kind.
{
       "objects": [
         {
           "a": 1,
           "prop":5
         },
         {
           "a": 1,
           "prop":6 
         } 
        ] 
}

I would be very grateful for any hints

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
Yuriyant, 2016-02-18
@yuriyant

In general, there is a solution to the problem and it is this:

db.test.aggregate([
  {
    "$redact": {
      "$cond": [
        {
          "$eq": [
            {
              "$size": {
                "$filter": {
                  "input": "$objects",
                  "as": "item",
                  "cond": {
                    "$eq": [
                      "$$item.a",
                      1
                    ]
                  }
                }
              }
            },
            2
          ]
        },
        "$$KEEP",
        "$$PRUNE"
      ]
    }
  }
])

R
Rostislav Grigoriev, 2016-02-17
@crazyzubr

db.users.find({'objects': {$elemMatch: {'a': 1}, $size: 2}})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question