Sambit
Sambit

Reputation: 464

Select the value from an array of hashes based on key from a single document in mongoid

I have a document in items collection like

// Document One
{
    "_id" : ObjectId("556411af73616d0d822f0000"),
    "visibility" : [
        {
            "user_id" : ObjectId("556412bb73616d0d82310000"),
            "visible" : false
        },
        {
            "user_id" : ObjectId("556412c973616d0d82320000"),
            "visible" : true
        }
    ]
},

// Some other documents
{...}
{...}

I want to get the value of visible only for "Document One" based on user_id I provide (eg. ObjectId("556412bb73616d0d82310000")).

How?

I am using mongoid 4.0.0.

Thanks.

Upvotes: 0

Views: 1202

Answers (2)

Neo-coder
Neo-coder

Reputation: 7840

You can do this in two ways :

1> Using $elemMatch and $ in projection as below

db.collectionName.find({"visibility":{"$elemMatch":{"user_id":ObjectId("556412bb73616d0d82310000")}}},
{"visibility.$visible":1,"_id":0})

it retunrns results as

"visibility" : [ { "user_id" : ObjectId("556412bb73616d0d82310000"), "visible" : false } ] 

this return whole matching array in visibility

2> Using aggregation as below :

 db.collectionName.aggregate({
   "$unwind": "$visibility"
 }, {
   "$match": {
     "visibility.user_id": ObjectId("556412bb73616d0d82310000")
   }
 }, {
   "$project": {
     "_id": 0,
     "visible": "$visibility.visible"
   }
 })

return results as { "visible" : false }

Upvotes: 1

Jonathan Lee
Jonathan Lee

Reputation: 136

Maybe you can try this:

db.one.find(
   {"visibility.user_id": ObjectId("556412bb73616d0d82310000")},
   {_id: 0, "visibility.$": 1})

In the query statementsdb.collection.find(query, projection), {"visibility.user_id": ObjectId("")} is used to select the required item, and {_id: 0, "visibility.$": 1} is used to show the specified field. What's more, $ operator (projection) is used to limit the output to be the matched one of array.

Official Doc: http://docs.mongodb.org/manual/reference/operator/projection/positional/#projection

$ The positional $ operator limits the contents of an from the query results to contain only the first element matching the query document. To specify an array element to update, see the positional $ operator for updates.

Use $ in the projection document of the find() method or the findOne() method when you only need one particular array element in selected documents.

Upvotes: 1

Related Questions