w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories
How to achieve row-level locking on an in-memory SQLite db?
It's not the filesystem that determines whether SQLite can lock rows. It's SQLite's architecture. Even using write-ahead logging, you can only have one writer at a time. Writers merely append new content to the end of the WAL file. Because writers do nothing that would interfere with the actions of readers, writers and readers can run at the same time. However, since there is only one WAL file, there can only be one writer at a time. SQLite3 has a kind of table locking now, but not row locking.

Categories : Database

Row level locking not working as expected in rails/mysql
I'm not quite sure why your updated code wouldn't work, but there is one odd thing about it: You're using lock! as though it returns a true/false value, but it can only ever return the model instance itself (if the lock is acquired) or raise an error (if acquiring the lock times out). This means lock_acquired will only be set to false if the lock actually is acquired, but the parent's status is not equal to 1. This code might behave more predictably: child.parent.with_lock do if child.parent.status == 1 child.parent.update_attributes(:status => 2) end # other code follows here end Note that with_lock behaves similarly to lock! -- either the block will be executed, or a lock timeout error will be thrown (after 50 seconds of waiting, under default MySQL settings).

Categories : Mysql

Supports transactions, row-level locking, and foreign keys
See http://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html If you re-create a table that was dropped, it must have a definition that conforms to the foreign key constraints referencing it. It must have the correct column names and types, and it must have indexes on the referenced keys, as stated earlier. If these are not satisfied, MySQL returns Error 1005 and refers to Error 150 in the error message, which means that a foreign key constraint was not correctly formed. If is rather difficult to guess as you didn't provide the definitions for the roles and permissions tables but to paraphrase the doc... ...in order to have a foreign key on a column, you must have an index on the "target" column. ...in order to have a foreign key on a column, both "source" and "target"

Categories : Mysql

How to avoid locking in mongodb
So i finally figured out some best way to avoid locking in mongodb. What i did Updated my mongodb to latest stable production release 2.4.8 from here. Updated my ebs to optimized iops 2000 with Raid 10 ebs. Monitored my slow queries from mongod.log file and also iowait for each drive. Added some multikey index and compound indexs From Mongodb indexs docs. And also i watched the consumption of ram on each ec2 instance including primary and secondary member of replica set. Change the instance type to Ebs optimized with Gigabit Ethernet interface and more than 16 gb of ram on each server so that most of the time ram is available for index and current data set . A good to read Documentation for amazon instance and their best use case so that you can understand your requirement better. A

Categories : Mongodb

Cassandra row level locking support while accessing same row by concurrent users
What you want is atomicity, Cassandra can syncronize with 1000 users, however it uses the timestamp to sincronize value in each column. You can use 'all' on consitence level for write and read, thereby to send and request the informations in all nodes, but maybe you can lost availability.

Categories : Cassandra

Mongodb: How to avoid locking on big collection updates
I think you are confused here, it is not the write lock causing that, it is MongoDB querying for your update documents; the lock does not exist during a page fault (in fact it only exists when actually updating, or rather saving, a document on the disk), it gives way to other operations. The lock is more of a mutex in MongoDB. Page faults on this size of data is perfectly normal, since you obviously do not query this data often, I am unsure what you are expecting to see. I am definitely unsure what you mean by your question: Question: How can I avoid those faults in order to be sure that all my events are correctly updated ? Ok, the problem you may be seeing is that you are getting page thrashing on that machine in turn destroying your IO bandwidth and flooding your working set wi

Categories : Mongodb

Implementing locking in a shared document editing environment.
If the documents are in a database, the database itself should have support for preventing inconsistent access. http://docs.oracle.com/javase/6/docs/api/java/sql/Connection.html#setTransactionIsolation%28int%29 If the editor does not keep database transactions/connections open for the duration of file editing, however, and the java application runs client-side rather than server-side (as you could simply create a lock in the editor for concurrency on the server side), then things get a bit trickier and I haven't yet had enough database experience to say how you would resolve that, as using a field in the database to indicate editing status would have concurrency problems with that type of setup (unless the database itself supports locking on records, but that would depend on the DB engin

Categories : Java

update nth document in a nested array document in mongodb
Q1: If you update with permalink 'jaiho' instead of 'haha', it most certainly updates the email; > db.posts.update({"permalink" : "jaiho"},{$set:{"comments.0.email":1}}) > db.posts.find() ..., "email" : 1 },... Q2: Same goes for this include; > db.posts.update({"permalink" : "jaiho"},{$inc:{"comments.0.num_likes":1}}) > db.posts.find() ..., "num_likes" : 1 },...

Categories : Arrays

MongoDB: If document exists VS If document does not exist
The question is how you determine that "the document" exists? Usually, you'd do this using a unique id. Now MongoDB's ObjectId comes to the rescue because it contains a timestamp already. This can also be used in queries. Instead of using an integer field User_ID, you might want to consider calling the field _id and use the ObjectId data type so you get that functionality for free. > db.test.insert({"foo" : "test"}); { "_id" : ObjectId("51cb763e58bb4077aea65b3d"), "foo" : "test" } > var foo = db.test.findOne(); > foo._id.getTimestamp(); ISODate("2013-06-26T23:16:14Z")

Categories : Mongodb

Mongodb: Store a tree as one nested document or store one document per node?
It looks like you are going to lots of operations in different levels of nested nodes in the tree. Although MongoDB can store a structure like you describe, it is not very good at allowing you to do update at lots of nested levels. Therefore I would recommend you to store each node as it's own document, and look at where you store the parent-child relations. Remember to optimise the schema for data operations. I'd go with your "way 1" in this case. If you would not have to change the tree a lot, and you have say 1000x more read than write operations to the tree, then you could consider using "way 2" and just deal with the extra work it takes to update the nodes at a few levels deep.

Categories : Json

To what level does MongoDB lock on writes? (or: what does it mean by "per connection"
It is not per connection, it is per mongod. In other words the lock will exist across all connections to the test database on that server. It is also a read/write lock so if a write is occuring then a read must wait, otherwise how can MongoDB know it is a consistent read? However I should mention that MongoDB locks are very different to SQL/normal transactional locks you get and normally a lock will be held for about a microsecond between average updates.

Categories : Mongodb

How to modify deeper level attributes in Mongodb?
You could use . notation Views.update({articleId:articleId}, { $push: {"promotions.0.viewerIps" :viewerIp} }, $set: {"promotions.0.promoterId":promoterId} }); The number there 0 comes from the index position in the array you want to alter. You can use the positional operator, $ to make a query on which array you want to alter. The reason i've used a number above instead of $ is that the $ isn't fully supported on meteor yet. You can use it only on the server if you want to. There is an open github ticket about this

Categories : Mongodb

Multi level MongoDB object querying by key
Unfortunately there is no wild card that allows you to search for a field at any level in the db. If the position is not relevant and you can modify the document structure you have 2 choices here. You can store your document as { fieldname:"nickname", value : "Howie" } { fieldname:"user/nickname", value: "Howie" } You can then query using db.so.find({fieldname:/nickname/, value:"Howie"}) Alternatively you can store as db.so.insert({value:"Howie", fieldpath:["nickname"]}) db.so.insert({value:"Howie", fieldpath:["user", "nickname"]}) The advantage with the second approach is that you can now index {fieldpath:1, value:1} and a query on it such as db.so.find({fieldpath:"nickname", value:"Howie"}) will be an indexed query.

Categories : Mongodb

Get the first document using $in with mongodb
You cannot add a limit to $in but you could cheat by using the aggregation framework: db.collection.aggregate([ {$match:{serial:{$in:[list_of_serials]}}}, {$sort:{_id:-1}}, {$group:{_id:'$serial',type:{$first:'$type'},sensors:{$first:'$sensors'},id:{$first:'$_id'}}} ]); Would get a list of all first found of each type. Edit The update will get the last inserted according to the _id.

Categories : Mongodb

Basic GROUP BY statement using OPA MongoDB high level API
I am afraid that, taking into account latest published Opa compiler code, no aggregation is supported :( See the thread in Opa forum. Also note the comment of Quentin about the using both low- and high-level API-s: "You can use this [low level] library and built-in [hight level] library together, [...]" See the auto-increment implementation advices by the guys from the MLstate in this thread. Note the high level DB field /next_id definition and initialization with low level read and increment.

Categories : Mongodb

How to use low-level driver APIs with Spring Data MongoDB
you can do it this way @Autowired MongoDbFactory factory; DB local = factory.getDB("local"); DBCollection oplog = local.getCollection("oplog.$main"); DBCursor lastCursor = oplog.find().sort(new BasicDBObject("$natural", -1)).limit(1); Where MongoDbFactory is an interface provifed by spring-data-mongo that can obtain a com.mongodb.DB object and access allthe functionality of a specific MongoDB database instance your configuration file should contain these informations : <bean id="mongoFactoryBean" class="org.springframework.data.mongodb.core.MongoFactoryBean"> <property name="host" value="127.0.0.1"/> <property name="port" value="27017"/> </bean> <bean id="mongoDbFactory" class="org.springframework.data.mongodb.core.SimpleMongoDbFacto

Categories : Spring

Why "Data at the root level is invalid. Line 1, position 1." for XML Document?
I can give you two advices: It seems you are using "LoadXml" instead of "Load" method. In some cases, it helps me. You have an encoding problem. Could you check the encoding of the XML file and write it?

Categories : Dotnet

mongodb - one document in many collections
Try looking at the problem inside-out: Instead of having items inside categories, have the items list the categories they belong into. You'll be able to easily find all items that belong to a category (or even multiple categories), and there is no duplication nor any need to keep many instances of the same item updated. This can be very fast and efficient, especially if you index the list of categories. Check out multikey indexes.

Categories : Database

How to sum every fields in a sub document of MongoDB?
You have made the classical mistake to have arbitrary field names. MongoDB is "schema-free", but it doesn't mean you don't need to think about your schema. Key names should be descriptive, and in your case, f.e. "S2" does not really mean anything. In order to do most kinds of queries and operations, you will need to redesign you schema to store your data like this: _id:... Segment:[ { field: "S1", value: 1 }, { field: "S2", value: 5 }, { field: "Sn", value: 10 }, ] You can then run your query like: db.collection.aggregate( [ { $unwind: "$Segment" }, { $group: { _id: '$_id', sum: { $sum: '$Segment.value' } } } ] ); Which then results into something like this (with the only document from your question): { "result" : [ {

Categories : Mongodb

Add a value to an array in a MongoDB document
You're looking for the $push operator. $arrayValueToAdd = array ( '22' => 1 ); $collection->update( array('email' => $user['email']), array( '$push' => array( 'emailQueries' => $arrayValueToAdd ) ) );

Categories : PHP

query the value of a sub document in mongodb
You can use dot notation in the projection parameter of find to do this. In the shell: db.test.find( {_id : ObjectId("5207fe359b88bfa6f90a82b0")}, {'members.5207fe359b88bfa6f90a82af': 1, _id: 0}) Returns: { "members": { "5207fe359b88bfa6f90a82af": [ "Admin", "User" ] } }

Categories : Mongodb

Capture Document-level Paste event without focused Input or Textarea
From http://www.w3.org/TR/clipboard-apis/ 5.1.3 paste event The paste event has no default action in a non-editable context, but the event fires regardless. Chrome uses a lazy paste event, which means that it doesn't check to see if the focused element is an editable content area, which is why the paste event works on the document. As for firefox and IE, it actually checks the element before letting allowing the paste event to be fired. So basically, you need an content editable element in order for the paste event to work in all browsers. I played around with using a content editable DIV as the main div on the page and I think it seems to produce the results you are looking for. Forgive me if the answer seems somewhat "hackish". You can place a contenteditable div as the containe

Categories : Javascript

XSLT 2.0: Limit the ancestor axes to a certain element/s level up the document tree
Well ancestor::*[level_c|level_b] selects all elements on the ancestor axis that have a level_c or level_b child. You might want (//level_d[not(level_d)])[last()]/ancestor::*[self::level_c|self::level_b]. Or with your textual description "to limit effectively the ancestors to level_b" you simply want (//level_d[not(level_d)])[last()]/ancestor::level_b.

Categories : Xslt

With cakephp2.3 and mongoDB how to add array in a document?
the answer to the question was: public function salvar($name,$size,$id){ $this->mongoNoSetOperator = '$push'; // fixed array data structure $susp = array( "_id" => $id, "images"=> array( array( 'id' => new MongoId(), 'name' => $name, 'size' => $size ) ) ); return $this->save($susp); } Note: Thank Garamon from github, by clear and objective answers.

Categories : Mongodb

delete element from document in MongoDB using C#
After searching on the web for a while, i found it myself. For those who want to know my solution: for (int j = 0 ; j < idlist.Count ; j++) { var queryDeleteValue = new QueryDocument("_id", idlist[j]); var update = Update.Unset("Flash_point"); collectionInput.Update(queryVerwijderValue, update); } So, first of all, i have a query-variable that selects the right document. Then i make an update variable where i unset the element 'Flash_point'. The last step is to do the actual update (with the parameters 'queryDeleteValue' and 'update').

Categories : C#

MongoDb c# update array in document
Working sample code for appending a list of strings to an existing list of strings using a strongly-typed Push: class Event { public ObjectId Id { get; set; } public string Name { get; set; } public List<string> Participants { get; set; } } class Program { static void Main(string[] args) { MongoClient client = new MongoClient("mongodb://localhost/test"); var db = client.GetServer().GetDatabase("test"); var collection = db.GetCollection("events"); var event0 = new Event { Name = "Birthday Party", Participants = new List<string> { "Jane Fonda" } }; collection.Insert(event0); collection.Update(Query.EQ("_id", event0.Id), Update<Event>.PushAll(p => p.Participants,

Categories : C#

Find document with its surroundings in MongoDB
You can not do this in one query, but you will have to use three instead: // current r = db.so.findOne( { _id: 6 } ); // previous 2 db.so .find( { publishDate: { $lte: r.publishDate }, _id: { $ne: 6 } ) .sort( { publishDate: -1 } ) .limit( 2 ); // next 2 db.so .find( { publishDate: { $gte: r.publishDate }, _id: { $ne: 6 } ) .sort( { publishDate: 1 } ) .limit( 2 );

Categories : Mongodb

mongodb update with many embedd document
When you call Save, base on your [BsonId] field driver decides what to do with this document: if document with Id does not exist in collection, it will insert this document if document with Id exists in collection, it will update this document (based on your Id). Update means it will replace all fields with the new fields from your entity Here is an example how save method works in pseudocode (the same as in C# driver): function save( doc ) { if( doc["_id"] ) { update( {_id: doc["_id"] }, doc, { upsert: true } ); } else { insert(doc); } }

Categories : Mongodb

mongodb c# how to work with BSON document
There are a few ways, but here's one: // build some test data BsonArray dataFields = new BsonArray { new BsonDocument { { "ID" , ObjectId.GenerateNewId()}, { "NAME", "ID"}, {"TYPE", "Text"} } }; BsonDocument nested = new BsonDocument { { "name", "John Doe" }, { "fields", dataFields }, { "address", new BsonDocument { { "street", "123 Main St." }, { "city", "Madison" }, { "state", "WI" }, { "zip", 53711} } } }; // grab the address from the document, // subdocs as a BsonDocument var address = nested["address"].AsBsonDocument; Console.WriteLine(address["city"].AsString); // or, jump straight to the value ... Console.WriteLine(nested["address"]["city"].AsString); // loop through the fields array

Categories : C#

Not able to delete document from Mongodb database with PHP
_id field is not a string in mongodb, it's an object of ObjectId class; instead of $id = (array("_id" => $_POST["id"])); you should use $id = (array("_id" => new MongoId($_POST["id"])));

Categories : PHP

Finding embedded document without _id in MongoDB
Yes, you can. Use the dot notation to specify the property of the embedded document you are looking for. Let's say you have a collection for persons with docs like this: { _id:123, name:"john", address: { Street:"any", zip:1234 } } Then you can find a person querying by an address field like this: db.persons.find("address.zip":1234, ...) Just consider that it won't give you only the embedded doc, but the entire document (person in this case)

Categories : Mongodb

Can I select an array from every document in mongodb?
You may need to use the Aggregation Framework to accomplish this. Specifically, $unwind. For example: db.blogPost.aggregate( { $project: { _id : 0 , comments: 1 } }, { $unwind: "$comments" } ); Alternatively, if viable in your situation, you could just perform the concatenation of comments at the application level instead of database level, making the Mongo query simply that of over all blog posts.

Categories : Mongodb

Single qoute in MongoDB document
I had same problem before 2 days and i have solved it using below query. below is the solution for me. SELECT * FROM tags WHERE `name` = 'limit\''s' LIMIT 0 , 30 SEE HERE

Categories : PHP

how to add and delete a sub document in MongoDB shell?
You are looking for $set and $unset. You would use it like so: db.collection.update({name: "John"}, {$unset: {"address.street": ""}, $set: {"address.zip": 94105}}) There is not a wildcard field name matcher in MongoDB. I don't anticipate one in the future.

Categories : Mongodb

How to remove a document referenced by an id in mongoDB from php?
"To remove a document based on its ID, you need to ensure that you pass the ID as a MongoID object rather than just a string:" Normally what the PHP manual states is true but not for you. You have changed the type of your _id to something other than an ObjectId (aka a MongoId). With this in mind you need to search by that other object which is a MongoInt32: $db->collection->remove(array('_id'=>new MongoInt32(1)))

Categories : PHP

How to push a new document in mongodb but only if it does not exist?
Use the $addToSet operator. It ensures that the value will be added if is not in the array already. Basically: exports.addContactPost = function(req, res, err) { User.findByIdAndUpdate(req.signedCookies.userid, { $addToSet: {friendRequest: req.body.friendRequest} }, function(err) { if(err) { console.log(err); return console.log('error'); } else { console.log('postsuccess'); res.json({response: true}); } }); };

Categories : Node Js

how to update a mongodb document from node.js?
Change this line: ({_id:doc._id},$set:{scores:zz}); To: ({_id:doc._id}, { $set:{scores:zz}} ); This should also probably be wrapped with a callback, to catch errors: db.schools.update({_id:doc._id}, {$set:{scores:zz}}, function(err, result) { if (err) //do something. });

Categories : Node Js

MongoDB (NoSQL) - Can a document reference/link to itself?
You can use the same thing in MongoDB i.e. Tomatoes can be main item with say _id=1 and these items will have parent id as 1. The collection can be noted as: { { 1, "Tomatoes", null }, { 2, "Tomatoes, Raw", 1 }, { 3, "Tomatoes, Canned", 1 }, { 4, "Tomatoes, Cooked", 1 } } Note that you can keep parentid in main item as null for query purposes (as I did above) or you can just remove that column if you do not need it (and it works as MongoDB is schema free.)

Categories : Mongodb

MongoDB C# driver upserting nested document
Try with $addToSet The $addToSet operator adds a value to an array only if the value is not in the array already. If the value is in the array, $addToSet returns without modifying the array. Something else you can do is to load your CoreElement and work with it in memory. You can add Suffs and MoreStuffs to the object checking for duplicates with C#. When you are finished with the object just save it, MongoDB will replace the object in the collection with your modified object.

Categories : Mongodb

inserting items in list in mongodb document
I found the answer, pretty foolish on my side; just have to remove extra braces {} Instead of this db.monitor.update({'_id' : 'dbjkdd'}, { '$push':{'pushed_list': {'$each':{lis1}}}}) Use this db.monitor.update({'_id' : 'dbjkdd'}, { '$push':{'pushed_list': {'$each':lis1}}}) i.e remove '{'after '$each' and its corresponding '}'

Categories : Mongodb



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.