How to get one particular object from collection's document array field?

In my collection Articles there is array field corrections with “copies” of articles.
Article object next to this:

{_id: 6369, 
  editedByUserId: "user1id", 
  staff: 'staff1', 

  corrections: [
   {_id: 6369, 
    editedByUserId: "user2id", 
    staff: 'corrected_staff2'
    }, 
   {_id: 6369, 
    editedByUserId: "user3id", 
    staff: 'corrected_staff3'
    }
  ]
}

I need to get one particular object from Articles.Corrections, by _id and editedByUserId
For example, by passing _id=6369 and editedByUserId="user3id" I expect object:

   {_id: 6369, 
    editedByUserId: "user3id", 
    staff: 'corrected_staff3'
    }

what I wanted is working in mongo shell with this expression:

db.articles.findOne({'_id': '6369', 'corrections.editedByUserId' : 'anonymous'}, {'corrections.$': 1}).corrections[0]

But when I tried make the same in meteor, I can’t get what I want.

doc = Articles.findOne({'_id': id, 'corrections.editedByUserId': correctionBy }, {fields: {corrections: 1, } } );

Code above returns whole array of corrections.

doc = Articles.findOne({'_id': id, 'corrections.editedByUserId': correctionBy }, {fields: {'corrections.$': 1, } } );

This code fires an error :

Exception in template helper: MinimongoError: Minimongo doesn’t support $ operator in projections yet.

I’m so tired, I tried hundred of combinations ( but still can’t figure out how to get one element from array…

You are working with minimongo, not mongo when doing a client side query. It is helpful to think of minimongo as a mongo-like addressable cache of the mongo objects, e.g. minimongo uses mongo selectors.

Because it is a client side cache it is very cheap to take in the entire document and then use regular js operations on it.

So, findOne based on your _id. Then parse the resulting document with regular js code (e.g. Array.find).

No data is going over the wire the only real cost is a little more copying.

side note

As a general rule, I avoid putting arrays in my documents and simply pay the price of having a lot of small documents. When I do that, then I can take advantage of many mongo querying features for speed of access and for scalability.

1 Like

Thanks, your advice has helped me.

1 Like

Happy to help! Cheers

1 Like

@brucejo, you helped me about getting one particular object from array. May be you’ll help and with setting it :blush: