1

I am new to MongoDB, my native language is Spanish. So I'm not sure how to find what I need.

I will try to make myself understandable.

my schema:

    let noticiaSchema = new Schema({
        titulo: {
            type: String,
            required: [true, 'El titulo de la noticia es requerido']
        },
        cuerpo_noticia: {
            type: String,
            required: [true, 'El cuerpo de la noticia es necesario']
        },
        publicacion_noticia: {
            type: Date,
            default: new Date()
        },
        actualizacion_noticia: {
            type: Date,
            default: new Date()
        },
        likes: {
            type: Array,
            default: []
        },
        foto: {
            type: String
        },
        dislikes: {
            type: Array,
            default: []
        }
    })

Sample Doc :

    {
        "_id" : ObjectId("5e81868faf9d6e084cc60cc8"),
        "titulo" : "fdsfsfs",
        "cuerpo_noticia" : "fdsfsfs",
        "actualizacion_noticia" : ISODate("2020-03-30T05:41:35.144Z"),
        "foto" : "14335143.png",
        "publicacion_noticia" : ISODate("2020-03-30T05:41:12.997Z"),
        "likes" : [ 
            "5e7ffb641650a326dcc1e1c7"
        ],
        "dislikes" : [],
        "__v" : 0
    }

I'm basically trying to query for an array of elements called likes, if an element is contained in this array I would want to return true / false on a new field.

Below is what I've tried, but it only returns the documents where the element exists in likes.

//5e7ffb641650a326dcc1e1c7  element to search
Noticia.aggregate([
{
    $match: {
        "likes": { "$in": ["5e7ffb641650a326dcc1e1c7"] },
        //likes is the array field with elements to search
    }
},
 {
     $project: {
        titulo: "$titulo"
    }
  }
 ], (err, trans) => {

})

I want it to return all my docs but with a field that tells me if this element is contained or not.

Finally, I want to know if there is a way to return the result by creation date, that is .sort {_id: -1}

whoami - fakeFaceTrueSoul
  • 17,086
  • 6
  • 32
  • 46
yavg
  • 2,761
  • 7
  • 45
  • 115

1 Answers1

2

If you wanted to return all docs, you should not be using $match, try below aggregation :

db.collection.aggregate([
   /** Add a field across all docs by checking on specific condition */
  {
    $addFields: {
      elementExists: {
        $cond: [{ $in: ["5e7ffb641650a326dcc1e1c7", "$likes"] }, true, false]
      }
    }
  },
  {
    $sort: {
      _id: -1 // Sort by '_id' field in descending order
    }
  }
]);

Test : mongoDB-Playground

whoami - fakeFaceTrueSoul
  • 17,086
  • 6
  • 32
  • 46
  • thank you very much, for now I just need to do it to search for a single string. Before I rate you I want to ask you something, with this query, could I also do operations such as return the total sum or the average of a field present in all the collections? – yavg Mar 31 '20 at 04:44
  • @yavg : If at all if you need to send input as an array, your `$cond` should've this :: `{$gt: [{$size: {$setIntersection: [["5e7ffb641650a326dcc1e1c7","5e7ffb641650a326dcc1e1c6"],"$likes"]}},0]}` – whoami - fakeFaceTrueSoul Mar 31 '20 at 04:48
  • @yavg : What do you mean by *present in all the collections* ? Do you mean all Docs ? Yes you can do it but you result structure might do change with new things being added to aggregation, you can ask for what exactly you're trying to do & required o/p.. – whoami - fakeFaceTrueSoul Mar 31 '20 at 04:50
  • Thanks, I was referring to a field present in the collection but that is not an array. Is it possible to get the sum / total average of this value in all collections? – yavg Mar 31 '20 at 04:50
  • @yavg : You can check (https://stackoverflow.com/questions/32234394/mongodb-sum-and-avg-of-sub-documents) or (https://stackoverflow.com/questions/23323515/mongo-average-aggregation-query-with-no-group) if those doesn't help you please raise a new question :-) – whoami - fakeFaceTrueSoul Mar 31 '20 at 05:00
  • can you give me a hand with this question please?: https://stackoverflow.com/questions/60960058/add-more-than-one-field-using-addfields – yavg Mar 31 '20 at 21:19