0

Considering:

{
  docs: Array[{field1, field2}]
}

I know how to find the document(s) containing field1 or field2 with $elemMatch, but my question is how can I get the value of field1 knowing field2?

I also know that in MongoDB you would use $elemMatch in the projection parameter. Or that I can do this in JS with something like _.find(), but the goal is to get only one specific document from Mongo.

Let say for example a document:

{
  _id: 1
  docs: [{a: 42, b:"stringX"}, {a:0, b:"stringY"}]
}

How can I get the value of a (42) knowing b ("stringX")?

Is there something like: MyCollection.findOne({_id: 1}, projection: {docs:{b: "stringX"}}) ?

Erdal G.
  • 1,830
  • 2
  • 19
  • 32

1 Answers1

1

On the server you can use this projection:

var a = MyCollection.findOne({'docs.b': "stringX"},{fields: {'docs.$': 1}}).a;

However the $ array projection does not work on the client in minimongo (yet).

Hopefully this is sufficient to get you unstuck.

See related question

Community
  • 1
  • 1
Michel Floyd
  • 16,271
  • 4
  • 21
  • 38
  • Thank you for your response. But my goal is not to get the first but the **specific** document. I already did it in JS with `_.find() ` but I'm looking for a Meteor / Mongo solution as lots of documents will be returned if I don't do it properly. _Just edited my question accordingly, sorry for the confusion_ – Erdal G. Dec 04 '15 at 00:52
  • Then you need `$elemMatch` in the projection! See http://stackoverflow.com/a/12241930/2805154 – Michel Floyd Dec 04 '15 at 01:38
  • As I said in the question, I know we can do it in Mongo with projection. My question is how to do it in Meteor collections ? – Erdal G. Dec 04 '15 at 01:42
  • A Meteor collection is a mongo collection. *Most* of the mongo syntax applies directly in Meteor. There are a few things that don't work or where the syntax is slightly different. – Michel Floyd Dec 04 '15 at 01:44
  • Ok, then can you give me the answer for my case please? :) Because I really looked everywhere on Meteor docs. Unlike Mongo, I don't see any "projection" option on Meteor's `.find()` or `.findOne()` methods. – Erdal G. Dec 04 '15 at 01:48