w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories
MongoDB update query (update an array field in document)
You are using the array operator push with a data structure that is not considered by MongoDb as an array (array must have 0-based ascending numeric indexes). You must treat it as an object. So you have 2 choices. If in [21] => 0, the value 0 is useless (and I don't expect so), you can use a true array: "emailQueries" : [21,22] and you can use the push operator in the PHP code like this $collection->update( array('email' => $user['email']), array( '$push' => array( 'emailQueries' => (string) $email_id ) )); On the other hand, if you must keep the value 0, and for instance, increment it, you have to considered your EmailQuery as an object : "emailQueries" : { "21" : 0, "22" : 0 } So you c

Categories : PHP

Meteor.js / MongoDB : finding a document's place in a collection
You can find out how many documents have larger popularity: var popularity = Documents.findOne(documentId).popularity; var morePopular = Documents.find({popularity: {$gt: popularity}}).count();

Categories : Javascript

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

Meteor/Mongodb find related records based on document's tags
It's easy with this structure: [{ title: 'title', tags: ['tag1', 'tag2'], }] Then you use: Documents.find({ tags: {$all: [ "alpha", "beta", "gamma" ]} }); See here: http://docs.mongodb.org/manual/reference/operator/all/#op._S_all Now, it may or may not work with complex objects as you have, I'm not sure. Try this: Documents.find({ tags: {$all: [{name: "alpha"}, {name: "beta"}]} }); If you need the specified structure and the above query does not work, you're left with the $where query. It is very flexible, but not recommended as it's much slower than the others. See here: http://docs.mongodb.org/manual/reference/operator/where/#op._S_where     EDIT: this one should do the job: Documents.find({ 'tags.name': {$all: ["alpha", "beta"]} });

Categories : Mongodb

mongodb: java: How to update a field in MongoDB using expression with existing value
At the moment, MongoDB doesn't allow you to update the value of a field according to an existing value of a field. Which means, you can't do the following SQL: UPDATE foo SET field1 = field1 / 2; In MongoDB, you will need to do this in your application, but be aware that this is no longer an atomic operation as you need to read and then write.

Categories : Java

Lucene 4.4: Update particular term's frequency in a document field without re-indexing the whole field
No, to update a document in Lucene, you must reindex the document. The process can be simplified using a call to updateDocument, but this doesn't simplify the operation on the backend. It still must delete the old document, and index a new one.

Categories : Solr

Update document in Meteor mini-mongo without updating server collections
There are some people working on local storage in the browser https://github.com/awwx/meteor-browser-store You might be able to adapt some of their ideas to provide "fake" documents.

Categories : Meteor

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#

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 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

Will mongodb take time to update the index when I update an unrelated field?
If you change the value of a or b during the update then the index will be updated. If you don't change either of the values, the index will only be updated if the document had to be relocated on disk during the update process. The way to tell for sure is to profile your updates - they are logged in mongod log if they take longer than 100ms but you can start mongod with a lower threshold (using --slowms switch) or you can turn on profiling for the DB in question with level 2 and then all operations will be logged into the system.profile collection. Read more about it here: http://docs.mongodb.org/manual/reference/command/profile/

Categories : Mongodb

How to retrieve array of specific field of sub document- mongodb
A normal MongoDB query will always give you the entire document with the same structure. If you want to get just part of the document or make a transformation to it you need to use the Aggregation Framework (is not as hard to understand as it looks, give it a try). In your case you might have to use $unwind in contacts to explode the array, $match to get only the account you want, and $project to present the data as you want.

Categories : Mongodb

MongoDB driver ruby, remove field in document
Your syntax looks slightly incorrect. As per docs: collection.update( { _id: @id }, { $unset: { herField: true } }, { multi: true }); Need the 'multi' option if you want to update multiple documents. E.g. from all records on this collection. http://docs.mongodb.org/manual/reference/operator/unset/#op._S_unset

Categories : Ruby

update the mongodb embedded document with $elemMatch
As per the documentation $elemMatch can be used for projection only. But i found an example which illustrate the use of $elemMatch in conjunction with $all. Try this out. 1) I created a document in collection in the following ways: db.testColl.insert({count:0,arr:[{token:'xya'},{token:'xyb'},{token:'xyc'},{token:'xyd'},{token:'xye'}]}) 2) then i use find command without db.testColl.find() Output: { "_id" : ObjectId("52345478ef5f122b1c9c54be"), "count" : 0, "arr" : [ { "token" : "xya" }, { "token" : "xyb" }, { "token" : "xyc" }, { "token" : "xyd" }, { "token" : "xye" } ] } 3) then i run the following command sequentially: db.testColl.update({arr:{$elemMatch:{token:'xya'}}},{'$inc':{'count':1}}) db.testColl.update({arr:{$elemMatch:{token:'xyb'}}},{'$inc':{'count':1

Categories : Mongodb

How to Update a Document in MongoDB w/Java Driver
I think your problem is here: criteriaObject.append( "_id", "ObjectId("520a56b730047339c26ec1fa")"); Should be: criteriaObject.append( "_id", new ObjectId("520a56b730047339c26ec1fa"); That way the field value is treated as an object id, not as string (containing the literal "ObjectId")

Categories : Java

Upserting a document with MongoDB, incrementing a field and setting it to 0 if not existent
You should either $set the values or update/replace the whole object. So either update(find_query, completely_new_object_without_modifiers, ...) or update(find_query, object_with_modifiers, ...) Plus, you cannot $set and $setOnInsert with the same field name, so you will start counting from 1 :) Oh, and you don't need to add the find_query items to the update_query, they will be added automatically. Try: col1.update( { user: accountInfo.uid }, { $set: { lastAccess: new Date() } $inc: { timesAccessed: 1 } }, { upsert: true, w: 1 }, function(err, result) { if(err) { throw err; } console.log("Record upsert as", result); });

Categories : Node Js

Renaming a field in an embedded Document in an Array in MongoDB not working
if you want to update it manually i suggest you will install rockmongo, rockmongo is a great tool working with mongo databases, just extract it on your server and connect to your database. there you will find very easy update to mongo database, tables and records. rock mongo

Categories : Arrays

update depending on item within document mongodb pymongo
hey just do something like this in pymongo from pymongo import MongoClient cursor_object = MongoClient()[your_db][your_collection] for object in cursor_object.find(): id = object['_id'] val1 = object['value1'] update = val1/2 cursor_object.update({"_id":id},{"$set":{"value2":update}})

Categories : Python

Unable to update mongodb document with special characters
MongoDB requires all strings to be valid UTF-8. It is quite likely that you are not sending valid UTF-8 into MongoDB, but instead for example have ® as ISO-8859-1 encoded characters. And MongoDB does not allow that.

Categories : Javascript

Spring-Data MongoDB Update all document fields
I am not sure that I 100% understand your question but it seems that you trying to migrate your data from a SQL database using Hibernate into MongoDB using Spring-Data. We recently migrated all of the binary data in our application from Apache Jackrabbit into MongoDB also with Spring-Data. In addition there was one instance where we were still storing some binary data in our SQL database which was also migrated: We migrated this data in the following manner: Retrieve all the entities required from hibernate. Create a new instance of your MongoDB document. Loop through all of these entities copying the data from hibernate entities onto the MongoDB document. Call MongoOperations#save() for each document. You also mentioned something about updating: To update a particular document just

Categories : Java

Is there a better way to update html based on input field reactively with Meteor.js?
1) Use the keyup event to detect when a new letter has been entered 2) Use normal jquery to get the value so do: Template.hello.events({ 'keyup #personName': function () { Session.set("personName", $("#personName").val()); } });

Categories : Jquery

In mongodb how do you do a pure update (not upsert) to replace an entire typed document?
Is Replace what you are looking for? var query = Query<MyModel>.EQ(m => m.Id, myModel.Id); var update = Update<MyModel>.Replace(myModel); var result = myCollection.Update(query, update, WriteConcern.Acknowledged); http://api.mongodb.org/csharp/current/?topic=html/5e30d03f-b26a-3840-ce84-222f9804ca92.htm And as Asya said, this will not perform an insert unless you explicitly use UpdateFlags.Upsert.

Categories : C#

Read image file into a MongoDB document's binary field via mongo shell script
I don't know of a way to read a binary file directly from the Mongo shell. However, I do know of a way to do it if you are willing to externally process the file and convert it to base64. Note that you have to perform some conversion anyway, since afaik, you cannot store raw binary data inside MongoDB. On Linux, I tried the following and verified it works: # Extract 1M random bytes, convert it to base64, and store it as /tmp/rrr $ head -c 10000000 /dev/random | base64 > /tmp/r $ mongo > var r = cat ('/tmp/r') # Reads into r BUT then terminates it with a NL > var rr = r.substring (0, r.length-1) # Remove the newline > var p = BinData (0, rr) # bring it into p

Categories : Image

Mongodb update array with another field
Try this: > db.c.find() { "_id" : ObjectId("51c156d25a334e9347b576a7"), "name" : "User1", "score" : "Good", "scores" : [ "Good", "Bad", "Average", "Bad" ] } > db.c.update({}, {$push: {scores:{$each:['111', '222'], '$slice': -4}}}) > db.c.find() { "_id" : ObjectId("51c156d25a334e9347b576a7"), "name" : "User1", "score" : "Good", "scores" : [ "Average", "Bad", "111", "222" ] } btw, I there is a problem with this kind of updates: if new object is grater then previous in size, it cause moving this object to another location on disk(e.g. you pushed "Average" and popped "Bad"). Updates "in-place" is faster, you can preallocate space for objects on first insert, like so: > db.c.insert({ "_id" : ObjectId("51c156d25a334e9347b576a7"), "name" : "<big_tmp_string>", "score" : "<

Categories : Arrays

Mongodb, update each field in Array
This is not possible in a single operation. You could update each subdocument value. Using getLastError from the update you can determine how many times you have to update eg: 1) Set all hasSeen values to false: db.test.update( { "cc.hasSeen": true}, { $set: { "cc.$.hasSeen" : false }}) while (db.getLastErrorObj()['n'] > 0) { db.test.update( { "cc.hasSeen": true}, { $set: { "cc.$.hasSeen" : false }}) } 2) Set user_id=2 has seen value to two: db.test.update( { "cc.user_id": "2"}, { $set: { "cc.$.hasSeen" : true }}) However, this does introduce a race condition as you have n operations instead of a single atomic operation.

Categories : Mongodb

Mongodb update type of field
You can use this command from mongo command line: db.MYCOLLECTION.find({ id_group: { $type: 2 } }).forEach(function(obj){ try { obj.id_group = parseInt(obj.id_group); db.MYCOLLECTION.save(obj); } catch(e) { // do something with error... } }); the id_group: { $type: 2 } tells mongo to load all the id_group which their value is a string. You can find more about mongo types here: http://docs.mongodb.org/manual/reference/operator/type/#op._S_type

Categories : Mongodb

Mongodb Update Query Deletes All Array Fields Except Field Specified in Command
You can update the time property of userCreated and leave the other properties alone by using dot notation: db.posts.update( { "_id" : { $exists : true } }, { $set : { "userCreated.time" : new ISODate("2013-07-11T03:34:54Z") } }, false, true )

Categories : Node Js

MongoDB - select document where all values in field array are present in a given array
Basically there are some ways to match array. There is no exact solution for your need. Considering you have documents like : { "_id" : ObjectId("51b05a712961f4704684d901"), "x" : [ 6, 7, 8, 9 ] } { "_id" : ObjectId("51b05a712961f4704684d902"), "x" : [ 7, 8, 9, 10 ] } { "_id" : ObjectId("51b05a712961f4704684d903"), "x" : [ 8, 9, 10, 11 ] } You can use query1 like: db.collection.find({x:[3,4,5,6]}) The result is exact match only for arrays like x result1: { "_id" : ObjectId("51b05a712961f4704684d8fe"), "x" : [ 3, 4, 5, 6 ] } query1 will not match : { "_id" : ObjectId("51b05a712961f4704684d8fe"), "x" : [ 3, 4, 5] } { "_id" : ObjectId("51b05a712961f4704684d8fe"), "x" : [ 3, 4, 5, 6, 7] } You can use : query2 like: db.t.find({x:{$all:[3,4]}}) result2 can be: { "_id" : ObjectI

Categories : Database

MongoDB,using java to update three fields of document at the same time,sometimes only two fields is updated
I've written a unit test to show how the code behaves. This unit test proves that: you should be able to update more than one field at once (i.e. multiple fields can be updated with the $set keyword) updateMulti will update all matching documents (Note, like all Java MongoDB tests this uses TestNG not JUnit, but it's pretty similar in this case) @Test public void shouldUpdateAllMatchingFieldsUsingMultiUpdate() throws UnknownHostException { MongoClient mongoClient = new MongoClient(); DB db = mongoClient.getDB("myDatabase"); DBCollection coll = db.getCollection("coll"); coll.drop(); //Put some test data in the database for (int i = 0; i < 5; i++) { DBObject value = new BasicDBObject(); value.put("fieldToQuery", "a"); value.put("ishi

Categories : Java

Meteor: meteor-collectionapi PUT overwrites the entire object instead of just updating the field I want
I'm guessing that bash is replacing "$set" with an empty environment variable eg. echo "$set" vs echo "$set" so update your PUT command to: curl -H "X-Auth-Token: 97f0ad9e24ca5e0408a269748d7fe0a0" -X PUT -d "{"$set":{"gender":"Female"}}" http://localhost:3000/collectionapi/players/8BW9Yg2oKByBGdnSa By default Collection.update() will replace a document if no modifiers are present ($set, $unset, $push, $pull etc). So the command being sent to the server is to replace the document with {"":{"gender":"Female"}}

Categories : Api

Meteor: display document's key and value without knowing the document itself?
Using Underscore.js you could loop through the unknown document and add the values/keys to an array. Using this array in the template will let you output all the keys/values. Like this (untested but should work): // Template js Template.whatever.elementToReturn = function() { var elementToReturn = []; var someDoc = CollectionWithUnknowFields.findOne({}); var index = 0; _(someDoc).each( function( value, key, someDoc ) { elementToReturn[index] = {}; elementToReturn[index]['value'] = value; elementToReturn[index]['key'] = key; index++; }); return elementToReturn; }; // Template HTML <template name="whatever"> {{#each elementToReturn}} <p>Key is: {{key}}</p> <p>Value is: {{value}}</p>

Categories : Meteor

Meteor Security: should all database insert, update, remove operation be a Meteor.call() to the server?
For the first point, you can choose any of the two possibilities, but i prefer to use the second one : Client can do insert/update/delete Server has some security checks With this system you use the latency compensation of meteor. So it seems to be a good way of doing. For the second point, you can imagine to store in Session where you are on the list when you click on the detail. Then when you come back to the list, you check the session value and you just have to use it to restore the state.

Categories : Javascript

Installing Meteor-Permission Denied/Run 'meteor update'
Delete all meteor folders In finder (cmd +shft+g) type in "~/.meteor" on the top of the finder window where is has the folder.meteor click and drag folder to trash 2. In finder (cmd +shft+g) type in "/usr/bin/meteor" then drag the meteor folder to trash 3.In /usr/ create a new folder "local" (password required) and inside "local" create a folder "bin" 4. Go back to terminal a run curl install.meteor.com | /bin/sh –

Categories : Meteor

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

How to add an additional field to Meteor.users collection (not within the Profile field)
You just add one. user.voted = false; If you want to access the field on the client side, make sure to create additional subscription channel for it. Meteor does not publish custom user properties by default.

Categories : Facebook

When update nested collection in meteor, how to pass variable for the update path
It doesn't work because you can't use dynamic keys for object literals in javascript. You need to use bracket notation and build up the object you want to use in the update. For example: var city = 'NYC'; var object = {}; object["address." + city] = 'new address'; MyCollectionName.update(idOfObjectToUpdate, {$set: object}); Your last example should work, assuming Collection is actually the name of a collection, and {sel} is the correct selector for what you are trying to do.

Categories : Javascript

Nodejs, MongoDB (node-mongodb-native). FindAndModify finds doc, but doesn't update it
In findAndModify, there is one more parameter which you can set, to return the old document(before update) or new document ( after update ). I am guessing this must be the issue. For confirmation, for the existing findAndModify() command, after this command is run, check that updated document from the mongo console, it must be changed.

Categories : Node Js

Meteor.js Mongodb access?
Meteor is using different binaries of mongo to keep the compatible version. If you want to test your mongo-shell commands or just play with it on the same version as meteor, create a meteor app and keep it running: meteor create testapp cd testapp meteor And in different shell (or tab) run meteor mongo The reason why it didn't work in your case: you didn't run mongodb server command mongod. But when you run your mongo app locally, it will run mongod with the correct set of flags and separate database file.

Categories : Osx

Meteor does not connect to MongoDB
Are you sure the problem is that Meteor doesn't connect to the database? You have several pieces here that have to work together. I don't see anything obviously wrong, but I would simplify the code to verify the problem is where you think it is. For example, try adding console.log(Posts.find()) to Meteor.startup on the server.

Categories : Mongodb

On Mac what is the best Data GUI for Meteor and MongoDB?
If you need a UI to look at Mongo database contents there are couple of options. If you want something Meteor specific, take a look at this atmosphere package: Houston Admin. It is a 3rd party package built by the community. For more general solution take a look at genghis, ruby gem with nice UI.

Categories : Mongodb



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