Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB $elemMatch in Meteor

I have a small question about $elemMatch. This is a document in MongoDB:

{
  _id:'asdf1234',
  latest: '2.0.0',
  foo : [{
    v : '1.0.0',
    text : "Hello"
  },{
    v: '2.0.0',
    text : "Hello v2.0.0"
  }]
}

I want to return only foo with v same as in latest field. For now I can do something like this:

var a = function(id, version) {
  //id = 'asdf1234'
  //version = '2.0.0'
  return MyCollection.findOne({_id:id}, {fields:{foo:{$elemMatch:{v:version}}});
}

and I will get foo array only with object with v:'2.0.0'. But now i want to get latest object in array, so parameter version will be 'latest' and function will look like this:

var a = function(id, version) {
  //id = 'asdf1234'
  //version = 'latest'
  if(version != 'latest') {
    return MyCollection.findOne({_id:id}, {fields:{foo:{$elemMatch:{v:version}}});
  } else {
    var doc = MyCollection.findOne({_id:id});
    //Some code to get object where v == doc.latest
  }
}

And now question - can I get element from foo Array only with one query, something like this:

MyCollection.findOne({_id:id}, {fields:{foo:{$elemMatch:{v:'$latest? or fields.latest?'}}});

I don't want to iterate through array to get latest element. Of course, if there is no chance to get it like this, I will write finding code :)

Thanks for any answers!

like image 876
Krzysztof Kukiełka Avatar asked Dec 06 '25 23:12

Krzysztof Kukiełka


1 Answers

Mongo find will give you the complete document with all entries in your array. It's not possible to select one of the foo array's items with a Mongo query. You need to find the correct subdocument once you have the array.

Fortunately, it's quite simple:

_.find(doc.foo, function(item) {return item.v === doc.latest});
like image 137
Hubert OG Avatar answered Dec 09 '25 15:12

Hubert OG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!