sql >> Database >  >> NoSQL >> MongoDB

MongoDB - Ontvang de nieuwste niet-null-veldwaarde uit documenten met tijdstempel

Je kunt dit proberen:

db.getCollection('test').aggregate([
    //Sort
    {$sort: { datetime: -1 }},
    //Add fields to an array
    {$group: {
        "_id": null,
        "field1": { $push: "$field1" },
        "field2": { $push: "$field2" },
    }},

    //Filter and do not include null values
    {$project: {
        "field1notNull" : {
              $filter: {
               input: "$field1",
               as: "f",
               cond: { $ne: [ "$$f", null ] }
            }
          },
        "field2notNull" : {
              $filter: {
               input: "$field2",
               as: "f",
               cond: { $ne: [ "$$f", null ] }
            }
          }
        }
    },
    //Get the first values of each
    {$project: {
        "_id": null,
        "field1": {$arrayElemAt: ["$field1notNull", 0]},
        "field2": {$arrayElemAt: ["$field2notNull", 0]} 
    }}
])


  1. MongoDB:Server heeft opstartwaarschuwingen

  2. Toon alle gegevens afkomstig van mongodb en render deze in de doT.js-templating-engine

  3. mongodb hoe te vragen met de nand-operator?

  4. MongoDB-equivalent van SQL OR