2

I tried to get the first element of an array of documents. As you can see, "primera" fiels is empty in the result:

{
"_id" : ObjectId("5bb164d71d2eef353d292cab"),
"asunto" : {
    "id" : "5b48bb7251b997b3cc23b9e4",
    "abreviatura" : "AF",
    "titulo" : "Alarma Fuente",
    "descripcion" : "Alarma generada por un evento de energía en la fuente."
},
"tiempos" : [
    {
        "cola" : "5b55f8a351b9979f1e417b43",
        "inicio" : 1538352343,
        "fin" : 1538353214,
        "total" : 871,
        "usuario" : {
            "id" : 0,
            "usuario" : "MOICA"
        }
    }
],
"pFecha" : "2018-09-30",
"primera" : [ ]

}

My query is:

var start = ISODate("2018-10-01T00:00:00.000Z");
var end = ISODate("2018-10-01T23:59:59.000Z");

db.moicaTickets.aggregate([

    { $match : { asunto:{$exists:true}, asunto: {$ne:null},tiempos:{$exists:true}, tiempos: {$ne:null},creado:{$exists:true}, "creado.lastEvent_tc": { $gt: start, $lt: end } }},
    { $project: { pFecha: { $dateToString: { format: "%Y-%m-%d", date: "$creado.lastEvent_tc", timezone: "-03:00" } }, asunto: 1, tiempos: 1, primera: "$tiempos.0"}}

         ]).pretty()

Thank you!

2
  • What does it mean get the first element of an array of documents. As you can see, "primera" fiels is empty in the result?? Please try to explain it more Commented Dec 12, 2018 at 17:28
  • "tiempos" is an array of elements (in this case, there is only one document). I want the field "primera" to be the first one of all these documents. Commented Dec 12, 2018 at 17:31

1 Answer 1

1

You can use $arrayElemAt to get any indexed element from the array

db.collection.aggregate([
  { "$project": {
    "pFecha": {
      "$dateToString": {
        "format": "%Y-%m-%d",
        "date": "$creado.lastEvent_tc",
        "timezone": "-03:00"
      }
    },
    "asunto": 1,
    "tiempos": 1,
    "primera": { "$arrayElemAt": ["$tiempos",0]}
  }}
])
Sign up to request clarification or add additional context in comments.

Comments

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.