Tuesday 23 May 2017

Return whole document in MongoDB with distinct fields and 1 select query

I'm having trouble writing a query that returns the whole document while still having 1 distinct field. I already tried to mess with Aggregates but to no avail. I already found this document after googling some time:

How to efficiently perform "distinct" with multiple keys?

It describes most of the solution i need, but i need to filter on another field as well.

This is the function I use right now to query a sorted list of the documents in the TempCollection.

function getLatestUserData(UserID, callback) {
  console.log("in func      " + UserID);
  Temp.find({ UId: UserID }).sort({ "created_at" : -1 }).exec( function (err, data) {
    console.log(data + "     " + err);
    callback(data);
  });
};

however, I cannot figure out how I can filter, sort and distinct all at the same time.

This is an attempt at using Aggregates, however, read articles for quite some time and I just can't figure out the syntax for the purpose I need:

function getLatestUserData(UserID, callback) {
  Temp.aggregate([

    {"$group": { "_id": { value: "$value", SerialNumber: "$SerialNumber" } }},
    {$filter : {input: "$UId", as: "UId", cond: {$U: [ "$UId", UserID ]} }}
  ]).exec( function (err, data) {
    callback(data);
  });
};

Here is a part of the TempCollection:

/* 1 */
{
    "updatedAt" : ISODate("2017-05-23T13:01:45.000Z"),
    "created_at" : ISODate("2017-05-23T13:01:45.000Z"),
    "UId" : "590b10221da091b2618a4913",
    "value" : 36,
    "SerialNumber" : "TEST2",
    "_id" : ObjectId("592432b9372464833d038b80"),
    "__v" : 0
}

/* 2 */
{
    "updatedAt" : ISODate("2017-05-23T14:23:39.000Z"),
    "created_at" : ISODate("2017-05-23T14:23:39.000Z"),
    "UId" : "58f8954c3602b80552b6f1fb",
    "value" : 39,
    "SerialNumber" : "IIOJOIMJ",
    "_id" : ObjectId("592445eb372464833d038bf4"),
    "__v" : 0
}

Any help is much appreciated!



via Krapton

No comments:

Post a Comment