Mongodb get records with priority

Asked

Viewed 231 times

0

I have 3 collections in Mongodb being two lists containing only one unique identifier and in collection remaining the unique identifier, name and surname. What I need to do is a query that is sorted by priority: who is on lista1 comes first, then who’s in lista2 and finally what is not only in the document of 3 fields. Someone can help me?

UPDATE: putting everything together in the same Collection is not an option, and in SQL it is done this way https://www.db-fiddle.com/f/do7HsPcFxvohS7TBth7Kmz/1

  • Hello, welcome to the site! Try to add examples of documents in your question, it is easier to understand what you need. A question that occurred to me here: what is the need to keep these data in three separate Ollections?

  • So Jorge, I’m very beginner in Mongo I’ll call list 1 the highest priority list 2 the second highest priority is the last the list, list 1 and 2 have only one field, which is let’s assume the CPF, whereas list 3 has CPF, name and surname, so I want to search the name Astolfo, will return me all occurrences of Astolfo, only that I wish that if any Astolfo has his number on the list 1 it appears first, so on

1 answer

0

Following the specifications you gave in the comment, I would add all the information in a single Collection.

It seems to me that you have three lists as input data. You could put the priority as a field within the document:

{
   "cpf" : 12345678900,
   "nome" : "Astolfo"
   "prioridade" : 1
},
{
   "cpf" : 98765432100,
   "nome" : "João"
   "prioridade" : 2
}

I considered that Astolfo was in the list 1 and João was in the list 2. You could do indexes with the fields you need to search, by CPF for example, and by the priority field. This way you need to maintain, query and update only one Colection. In the end just sort the query by priority:

      db.pessoas.find({"cpf":12345678900},{"prioridade":1})

If there are two documents with the same CPF on Collection they will appear in the priority order.

  • Unfortunately joining all in a single Collection is not an option :( in SQL would be done this way https://www.db-fiddle.com/f/do7HsPcFxvohS7TBth7Kmz/1

  • Why is it not an option to join in a Collection? You even have an operator to do left Oin on Mongo, in which case doing so would pervert the bank for your need. You should choose the bank according to need.

  • Actually it’s an option, as long as I can do this Merge, why am I importing all this information from 3 csv files

  • In Mongo there is no problem for you to have documents with different fields. Using Mongo, I believe the best way out is to import in a single Collection.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.