Updating an array field that contains hashes in mongoid - ruby-on-rails

I have a document in XYZ collection as follows.
"_id" : ObjectId("55311e4487216d7063040000"),
"colours" : [
{
"value" : 1,
"colour" : "red"
},
{
"value" : 2,
"colour" : "green"
}
]
I need to update the name of the colour which value is 1. What query should I write?
I am using rails 4.1.2, mongoid 4.0.0.
Please help.

For example you want to change it to "yellow" :
XYZ.where(_id: "55311e4487216d7063040000").elem_match(colours: { value: 1 }).update("$set" => {"colours.$.colour" => "yellow"})

Related

how to iterate through json result in ruby on rails?

I have a function in ruby on rails, where I make a call and get the following json data. now i want to add another “key” : "value" to each item in the json data and return the new or modified json object from the function. what is the best way to do this in ruby?
def get_results
results = getJsonData();
end
[
{ "name" : "Harry Potter", "rating" : 1, },
{ "name" : "Lord of the rings", "rating" : 2, },
{ "name" : "game of thrones", "rating" : 3, },
]
You can use map to transform every element of a collection
def get_results
results = getJsonData();
results.map { |item| item.merge("year" => 2000) }
end
In this case I'm adding a key "year" to your hashes with value 2000, it depends what you want to do

MongoID : match multiple elements in array and update all

I use MongoID and PostgreSQL on Rails 4 and I have a notification system.
Each user has one notification document. I would like to be able to mark all as read in a controller.
Here is my notification schema :
{
"_id" : ObjectId("53e360156d6163513e000000"),
"unread_counter" : 1,
"user_id" : 1,
"rows" : [
{
"_id" : ObjectId("53e369166d61635328000000"),
"readed" : false,
"created_at" : ISODate("2014-08-07T11:55:02.936Z"),
"author" : {
"_id" : ObjectId("53e369166d61635328010000"),
"username" : "edouard",
"user_id" : 6
},
"subject" : {
"_id" : ObjectId("53e369166d61635328020000"),
"type" : "follower"
}
}
]
}
The problem is that elem_match just match one element in rows array.
Notification.where(:user_id => current_user.id)
.elem_match(rows: { readed: false })
.update_all("$set" => {"rows.$.readed" => true })
I have been inspired by this post : mongoid update elements within array
How can I match all "readed" : false row elements and then update them to true ?

mongodb: best way to get specific documents and then the rest

lets say I have 1000 documents where each one has:
user_id
text
Now, I would like to pull all those documents but first pull the documents from a few specific users (given an array of user ids) and then all the rest.
I was thinking to use map reduce to create a new weight inline attribute if the user_id exists in the specific users array (using scope to pass the array) and then to sort that new attribute. But from what I could understand, you can not sort after map reduce.
Any one has a good suggestion how to pull this off? Any suggestion will be welcome.
Thanks!
Well there isn't a lot of detail here, but I can give a sample case for consideration. Consider the following set of documents:
{ "user" : "fred", "color" : "black" }
{ "user" : "bill", "color" : "blue" }
{ "user" : "ted", "color" : "red" }
{ "user" : "ted", "color" : "black" }
{ "user" : "fred", "color" : "blue" }
{ "user" : "bill", "color" : "red" }
{ "user" : "bill", "color" : "orange" }
{ "user" : "fred", "color" : "orange" }
{ "user" : "ted", "color" : "orange" }
{ "user" : "ally", "color" : "orange" }
{ "user" : "alice", "color" : "orange" }
{ "user" : "alice", "color" : "red" }
{ "user" : "bill", "color" : "purple" }
So suppose you want to bubble the items for the users "bill" and "ted" to the top of your results, then everything else sorted by the user and the color. What you can do is run the documents through a $project stage in aggregate, as follows:
db.bubble.aggregate([
// Project selects the fields to show, and we add a weight value
{$project: {
_id: 0,
"user": 1,
"color": 1,
"weight": {$cond:[
{$or: [
{$eq: ["$user","bill"]},
{$eq: ["$user","ted"]}
]},
1,
0
]}
}},
// Then sort the results with the `weight` first, then `user` and `color`
{$sort: { weight: -1, user: 1, color: 1 }}
])
So what that does is conditionally assign a value to weight based on whether the user was matched to one of the required values. Documents that do not match are simply given a 0 value.
When we move this modified document on to the $sort phase, the new weight key can be used to order the results so the "weighted" documents are on top, and anything else will then follow.
There a quite a few things you can do to $project a weight in this way. See the operator reference for more information:
http://docs.mongodb.org/manual/reference/operator/aggregation/

Restkit mapping 0.2

How to map a json like this in Restkit 2.0.I can't find a tutorial and all tutorials there is for previous versions.I know how it is done in 0.10.0 but dont have an idea how to do this array and nested arrays in 0.20.0
{
"days" : [
{
"day" : 1,
"id" : 1,
"set1" : [
{
"exercise_id" : 1,
"exerciseunits" : [
{
"count" : 3,
"id" : 1,
"weight" : 60
}
],
"id" : 1,
"name" : null,
"subbodypart_id" : 1,
"subbodypartname" : "Chest"
}
]
}
],
"description" : "desc",
"id" : 1,
"name" : "asdfg"
}
Use the updated documentation in the wiki about object mapping. More than that you can download the current RestKit master with examples (e.g. Twitter Core Data) where nested objects are used as well.

MongoDB/Mongoid: Can one query for ObjectID in embedded documents?

For the record, I'm a bit of a newbie when it comes to Rails and MongoDB.
I'm using Rails+Mongoid+MongoDB to build an app and I've noticed that Mongoid adds ObjectID to embedded documents for some reason.
Is there any way to query all documents in a collection by ObjectID both the main documents and nested ones?
If I run this command
db.programs.findOne( { _id: ObjectId( "4d1a035cfa87b171e9000002" ) } )
I get these results which is normal since I'm querying for the ObjectID at root level.
{
"_id" : ObjectId("4d1a035cfa87b171e9000002"),
"created_at" : "Tue Dec 28 2010 00:00:00 GMT+0000 (GMT)",
"name" : "program",
"routines" : [
{
"name" : "Day 1",
"_id" : ObjectId("4d1a7689fa87b17f50000020")
},
{
"name" : "Day 2",
"_id" : ObjectId("4d1a7695fa87b17f50000022")
},
{
"name" : "Day 3",
"_id" : ObjectId("4d1a76acfa87b17f50000024")
},
{
"name" : "Day 4",
"_id" : ObjectId("4d1a76ecfa87b17f50000026")
},
{
"name" : "Day 5",
"_id" : ObjectId("4d1a7708fa87b17f50000028")
},
{
"name" : "Day 6",
"_id" : ObjectId("4d1a7713fa87b17f5000002a")
},
{
"name" : "Day 7",
"_id" : ObjectId("4d1a7721fa87b17f5000002c")
}
],
"user_id" : ObjectId("4d190cdbfa87b15c2900000a")
}
Now if I try to query with an ObjectID with one of the embedded document (routines) I get null like so.
db.programs.findOne( { _id: ObjectId( "4d1a7689fa87b17f50000020" ) } )
null
I know one can query embedded objects like so
db.postings.find( { "author.name" : "joe" } );
but that seems a bit redundant if you get passed an ObjectID of some sort and want to find in what document that ObjectID resides.
So I guess my question is this...
Is it possible, with some method I'm not familiar with, to query by ObjectID and search the ObjectID's in the embedded documents?
Thanks.
You can't query ObjectIDs globally like that. You would have to do
db.programs.find({"routines._id": ObjectId("4d1a7689fa87b17f50000020")})
no, you can search only by field like { "routines._id" : ObjectId("4d1a7689fa87b17f50000020")}
If you want to get the matched sub-document only you can use $elemMatch with '$' operator like below:
db.programs.find({"_id" : ObjectId("4d1a035cfa87b171e9000002"),
routines:{$elemMatch:{"_id" : ObjectId("4d1a7689fa87b17f50000020")}}},{"routines.$":1})
It will return you only that matched sub-document instead of the complete sub-document.

Resources