I
I
Ilya Karavaev2017-04-10 09:20:21
MongoDB
Ilya Karavaev, 2017-04-10 09:20:21

Is it possible to get a record with one nested element?

Hello.
I've been digging through the documentation and can't seem to find an answer to a seemingly simple question. Is it possible to pull a record from a collection with a single nested element from the list with one query (aggregation)?
In general, there is a record, in the data field there is a list of nested elements with search keys and other information, there can be up to 8000 such elements in the field. Getting a document and processing it in a loop is not the best option. It would be desirable to receive the document with the superfluous data already cut off.
Document example:

{ 
    "status" : NumberLong(1), 
    "data" : [
        {
            "subject" : {
                "docNumber" : "0000 000000", 
                "fname" : "Васильев", 
                "mname" : "Васильевич", 
                "lname" : "Васильев"
            }, 
            "applications" : [
                {
                    "number" : "ДОК-00022325", 
                    "info" : "..."
                }
            ], 
            "documents" : [
                {
                    "number" : "ДОК-00022325", 
                    "info" : "..."
                }
            ]
        }
    ]
}

Accordingly, I only need to get a list of all documents that match number DOK-00022325 and get information from the info field from the bottom (there may be several entries in the collection that satisfy the search conditions), in any format. Working with a small amount of data is easier than iterating over thousands of rows.
Is it possible to implement this on the MongoDB side?
UPD:
Got to the bottom of this option. But if there are other suggestions, I'll read it again.
aggregate(
  [
    {
      $match: {
      	"data.documents.number": "ДОК-00022325"
      }
    },
    {
      $unwind: "$data"
    },
    {
      $match: {
      	"data.documents.number": "ДОК-00022325"
      } 
    }
  ]
);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
lega, 2017-04-10
@Quieteroks

You can change the schema so that number is the key, like so:

documents: {
  "ДОК-00022325": {info:''},
  "ДОК-00022326": {},
}

and a simple query:
.findOne({_id: xxx}, {'documents.DOC-00022325.info': 1})
But it's better to use a hash of the document number, and store the number inside so that there is no conflict of characters in the key.
You can also use https://docs.mongodb.com/manual/reference/operator...
for arrays. And if you need to search for a number in the entire collection, then there must be an index for the number, otherwise there will always be a complete enumeration of the base and the brake. It's better to change the pattern.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question