MongoDB/mongoid update_attributes method slow?
I have some code where I need to update a record in my mongoDB DB. So I first find the record and then I update the record. However, the records have lots of text data stored with them, so I don't want to retrieve the entire document when I get it back; just enough so that I can update it. I thought that if I used the "only(...)" method in mongoid, that this would return only that attribute. These queries seem to be running very slow, though, so I was not sure if they were accomplishing what I thought they were accomplishing.
d = Document.only(开发者_如何学运维:title).find(title) # using 'title' as key in mongoDB
d.update_attributes({ author: "author_name" })
Is there a faster way to execute this desired query?
MongoDB offers a number of highly-optimized modifier operations. Look into using the $set
operation to set only a single key without having to deal with the rest of the document. You can also do the update and the query in a single operation. A native MongoDB query to update the author
of all records with the specified title
would look like this:
var title = "The Title"
db.documents.update( { title: title }, { $set: { author: "The Author" } } )
Hopefully you can find a way to pass that query along through Mongoid. If not, you can go directly down to the native Mongo adapter to run it. For more info, see the docs on modifier operations.
One thought I have is that you could break up the collection into two collections: one that has the metadata of the text (name, author, yearPublished, numPages, etc), and another that has a foreign key(which could just be MongoDB's _id) and the text itself. Then you can modify things like author name on the smaller collection, which I believe would perform faster... Something to test, I guess. However, I think your speed issues are due to the size of records. I personally noticed a significant loss in performance going from a simple test dataset without many attributes to a real dataset with many attributes per record.
精彩评论