Retrieve each record satisfying list of conditions


#1

I want to retrieve each record for different values of a key. For example I have a below collection

{ "_id" : ObjectId("583342efb60a1642ae70ec9d"), "name" : "xxx", Data" : 111}
{ "_id" : ObjectId("583342efb60a1642ae70ec9d"), "name" : "xxx", Data" : 222}
{ "_id" : ObjectId("583342efb60a1642ae70ec9d"), "name" : "yyy", Data" : 333}
{ "_id" : ObjectId("583342efb60a1642ae70ec9d"), "name" : "yyy", Data" : 444}
{ "_id" : ObjectId("583342efb60a1642ae70ec9d"), "name" : "zzz", Data" : 555}

From the above collection I want single record for each key - “name”. I want retrieval output as

{ "_id" : ObjectId("583342efb60a1642ae70ec9d"), "name" : "xxx", Data" : 111}
{ "_id" : ObjectId("583342efb60a1642ae70ec9d"), "name" : "yyy", Data" : 333}
{ "_id" : ObjectId("583342efb60a1642ae70ec9d"), "name" : "zzz", Data" : 555}

I’ve tried lot of queries using findone, aggregate, group, match, distinct, etc ,… Basically I tried to find

db.collection.find({"name" : ["xxx", "yyy","zzz"]}).limit(1)

The above query will retrieve only one record. But i’m not sure how to club the queries to get one on each key value for the key - “name”

Any help would be appreciable. Thanks in advance.


#2

https://docs.mongodb.com/manual/reference/method/db.collection.distinct/


#3

@rhywden - Thanks for your response. But unfortunately I want the last entire record and not just the field.


#4

There’s no out-of-the-box solution for that and you’ll have to do some work yourself.

Use distinct to get the unique field entries and then do a results.forEach on the resulting array to get the last document containing the field by a search for said field.


#5

@rhywden - I tired to run query using results.forEach for the distince array of values. I am not getting correct output. Can you please provide a sample query based on the above example? Thanks in advance


#6

Okay. First of all, the distinct() command is not available on minimongo, so you’ll have to access the raw collection which you can only do on the server. Basically, create a Meteor method on the server, query the RawCollection and return an array of values.

Meteor.methods({
  rawFind(): function() {
    let rawCol = CollectionName.rawCollection();
    return rawCol.distinct("name");
  }
})

On the client you can then do this:

Meteor.call("rawFind", function(error, result) {
  if(!error) {
    let result = CollectionName.find({"name" : result});
    //do whatever you want with the result
  }
});

This is not reactive, however.

Then again, a short Google search might also have turned up this for you: