4

I have this document:

...
    "username" : "torayeff",
    "profile" : {
        ...
        "friends" : [
            {
                "_id" : "aSD4wmMEsFnYLcvmP",
                "state" : "active"
            },
            {
                "_id" : "ShFTXxuQLAxWCh4cq",
                "state" : "active"
            },
            {
                "_id" : "EQjoKMNBey7WPGamC",
                "state" : "new-request"
            }
        ]
        ...
    }
...

This is query for getting only "state" attribute of given user:

Meteor.users.findOne({_id: userId1, 'profile.friends._id': userId2}, 
                    {fields: {_id: 0, 'profile.friends.state.$':1} });

In meteor I am receiving this error:

Exception while simulating the effect of invoking 'activateFriendship' Error: Minimongo doesn't support $ operator in projections yet...

How can I rewrite above query without having error in minimongo?

torayeff
  • 9,296
  • 19
  • 69
  • 103

2 Answers2

-1

Use $elemMatch for finding nested array, and $ in your projection, so query as below :

Meteor.users.findOne({
  "_id": userId1,
  "profile.friends": {
    "$elemMatch": {
      "_id": userId2
    }
  }
}, {
  "profile.friends.state.$": 1
})
Neo-coder
  • 7,715
  • 4
  • 33
  • 52
-1

you can do like

EDIT : if you just want to grab the values without keys, use this

Meteor.users.distinct('profile.friends.state', {_id: userId1, 'profile.friends._id': userId2});

For usual cases :

Meteor.users.findOne({_id: userId1, 'profile.friends._id': userId2}).select({ _id: 0, 'profile.friends.state':1 }).exec()

$ project operator not required

codeofnode
  • 18,169
  • 29
  • 85
  • 142
  • this will return ["state" : "active", "state" : "active", "state" : "new-request"] while I need only 1 element, that is why I am using .$ – torayeff Apr 30 '15 at 14:51
  • This answer misses the point: how to get only the *one whole* object in the array that matches the query. – T3db0t Apr 07 '16 at 20:33