Only showing results of 1 sub-document / array item in view


I’m a little stuck.

I have a collection setup something like

    _id: someIdHere,
    name: {
        first: Brian,
        last: McGonagill
    phone: {
        home: 800-555-1234,
        cell: 800-444-1414
    gender: M,
    gifts: [{
            giftNo: 1,
            giftType: Pajamas,
            giftSize: XL,
            giftNo: 2,
            giftType: Winter Hat,
            giftSize: 9 1/2,

I’m running a query to try and get only one gift from the array by giftNo. It works in the Meteor Mongo cli, as follows:

db.recipients.find({ _id: "DKnjEEE9rGpFqJcAW", "gifts.giftNo": "2"  }, { "gifts.$": 1 })

Of course in code I replace the ID number with a variable, and the gift Number with a variable. In the CLI this gives

    "_id" : "DKnjEEE9rGpFqJcAW",
    "gifts" : [
		    "giftNo" : "2",
		    "giftType" : "Winter cap&scarf",
		    "giftSize" : "one size fits all",

Which is what I want.

When I use it in a helper, however, and I do

{{#each myHelperFunction}}

I only get [Object], [Object]…so I added a second loop…

{{#each myHelperFunction}}
    {{#each gifts}}

This works, sort of, but I get all gifts and sizes for this _id. So, I did some testing, and it appears that Meteor is ignoring the last part of the query which tells Mongo that I only want the first match found, which in this case is only 1 gift.

Any help on how I can resolve this is much appreciated.


You should use db.recipients.findOne({...})

It will return and fetch only one result


Ok @n1s , so how do I use that in a helper? I get an error about {{#each}} needing to be an array.

Also, when I run

Recipients.findOne({ _id: "DKnjEEE9rGpFqJcAW", "gifts.giftNo": "2"  })


Recipients.findOne({ _id: "DKnjEEE9rGpFqJcAW", "gifts.giftNo": "2"  }, { "gifts.$": 1 })

I still get all data back for that _id, including all gifts, not just giftNo 2.

As I stated before, the last part of my query in the code { “gifts.$”: 1 } is seemingly being ignored by Meteor, and I get all gifts back in my code, whereas using that in the Metoer Mongo CLI only gives the 1 gift back.


So I found this on the forums, and tried it, but also got an error:

Groups.findOne({ _id: recipientId, "gifts.giftNo": setGiftNo }, 
  fields: {"Igifts.$.giftType": 1}

I get an error about the $ positional operator not being supported in mini mongo yet.

That possible solution came from this post on the forums,

Still looking for a way to only get back one of the gifts vs. all of them.