Home > Back-end >  mongodb Show all elements except one depending on the value of a date
mongodb Show all elements except one depending on the value of a date

Time:10-14

I'm starting to learn MongoDB, and I love how flexible it is.

But I'm stuck on a query, and i would like to know the solution.

I have got a collection that goes like:

{
"_id" : ObjectId("633e08f5edef7d5ffc6d0583"),
"etiquetaPrincipal" : "Inteligencia artificial",
"titular" : "¿Puede una máquina decidir cuánto debes cobrar?",
"subtitulo" : "Las empresas recurren a la inteligencia artificial para su política salarial, pero aún es imprescindible la supervisión humana para evitar sesgos o errores",
"autor" : "Raúl Limón",
"fecha" : ISODate("2022-10-04T05:20:00.000 0000"),
"etiquetas" : [
    "Tecnología",
    "Inteligencia artificial",
    "Economía",
    "Salarios",
    "Computación",
    "Mercado laboral",
    "Ética científica",
    "Ética",
    "Aplicaciones de Inteligencia Artificial",
    "Aplicaciones informáticas"
],
"noticia" : "¿Cuál es el salario justo? ¿Puede la inteligencia artificial establecerlo? Kotaro Hara, profesor de ciencias de la computación en la Universidad de Singapur cree que la primera pregunta plantea “un problema que necesita ser resuelto con urgencia”. Al fin y al cabo, un pacto de rentas es una de las soluciones propuestas ante la situación de crisis actual. A esto se une la precarización extrema de sectores menos cualificados —empleados en reparto o tareas domésticas pueden ganar entre 9 y 14 euros por hora— y, en el frente contrario, la guerra salarial abierta para atraer a los trabajadores más vinculados a sectores tecnológicos, donde más demanda se registra. La segunda cuestión —si puede la inteligencia artificial establecer el salario justo— tiene respuestas contradictorias: sí, porque puede aportar las herramientas para establecer cuánto se paga por una tarea determinada; pero no, porque sin supervisión humana, el algoritmo puede llevar a decisiones equivocadas. Aun así, muchas empresas empiezan a utilizar la inteligencia artificial para fijar sus políticas salariales."}

My query has to:

Show all the fields except "etiquetas" of the news from September-29-2022

how do i do that?

CodePudding user response:

Assume that you want to remove the field based on fecha value,

  1. $set - Set etiquetas field

    1.1. $cond - Compare fecha value is greater than 2022-09-29

    1.1.1. If true - remove the field.

    1.1.2. Else - remain the value.

db.collection.aggregate([
  {
    $set: {
      etiquetas: {
        $cond: {
          if: {
            $gt: [
              "$fecha",
              ISODate("2022-09-29T00:00:00Z")
            ]
          },
          then: "$$REMOVE",
          else: "$etiquetas"
        }
      }
    }
  }
])

Demo @ Mongo Playground


Reference

Exclude Fields Conditionally

CodePudding user response:

The wording in the question is a little ambiguous. What does "from September-29-2022" mean specifically?

Generally speaking, @Yong Shun Yong's answer is helpful in demonstrating how to conditionally exclude fields. In particular it will retrieve all documents from the collection, but will only remove the etiquetas field for those with a date after 29 September.

Other possible interpretations are:

  1. That all document should be returned, but only those with a date of 29 Sept should have the etiquetas field removed. In this case you should definitely use the other answer as a starting point and add a $lt clause to the if condition (wrapping the two in an $and).
  2. That the query should only return documents that are from 29 Sept or later.
  3. That the query should only return documents with a date of 29 Sept (not before or later).

If 2. above is the correct interpretation, then your query would look something like this:

db.collection.find(
  { "fecha": {  $gt: ISODate("2022-09-29T00:00:00Z") } },
  { etiquetas: 0 }
)

Associated playground link is here

And 3. is what is needed, then you can add the $lt predicate to the above query.

Overall it is important to be specific about what logic you are requesting as the associated query to accomplish it may look very different.

  • Related