spot7.org logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories
  Home » MONGODB » Page 1
Where will MongoDB "forEach" commands run?
You could use eval function to run code on the MongoDB server. For example: db.eval(function() { db.Products_PoC.find().forEach( function(myDoc) { myDoc.price = (myDoc.price.toFixed(2)) * 100; db.Products_PoC.save (myDoc); }); }); More about eval here. Pay attention that db.eval will take global write lock on your database.

Categories : Mongodb

MongoDB tag range not working
It looks like you are trying to distribute a single collection across two shards, but have defined overlapping shard tag ranges where site_A and site_B include the whole range of shard.target key values (minkey .. maxkey): tag: site_A { "shard" : { "target" : "siteA", "key" : { "$minKey" : 1 } } } -->> { "shard" : { "target" : "siteA", "key" : {

Categories : Mongodb

MongoDB - make replica set member passive without disconnecting clients?
Instead of reconfiguring the replica set, you can run rs.freeze(...) on the secondary you are running the backup on. A frozen secondary will be ineligible to become primary during the specified period. Once the backup is complete, you can then run rs.freeze(0) on the secondary to unfreeze it. Caveats to consider: You should ensure there are sufficient data-bearing nodes in the replica set to e

Categories : Mongodb

Is it possible to ensure uniqueness on a sharded hashed key in MongoDB?
OK so our solution was sharding on the _id (which has a forced unique index per Mongod/shard instance) and adding a hashed(_id) index which we sharded on. This ensures that all items are unique.

Categories : Mongodb

Spring Data (mongoDb) + @Id element + EJB + DBRef. Cannot create a reference to an object with a NULL id
I'm a fu..g stu..d guy, this is not a matter of spring or mongo it's a matter of EJB. Obviously the object is passed, spring data update the id but IT'S a REMOTE EJB!!! and it's not passed by reference. There is at least a couple of solutions but the best one is to return back the updated object. I hope it helps to anybody. Cheers.

Categories : Mongodb

Mongo Db optimized query
One optimization is to add the variable field to the index. Just to demonstrate its effect. Let values be a collection having just three documents, two of which match the variable we are looking for. Sample data: db.values.insert([{ "_id" : 1, "dateNum" : 41274, "source" : [ { "value" : 625, "formatCode" : "General" } ], "variable" : 1 }, { "_id" : 2, "dateNum" : 41274

Categories : Mongodb

how to set the data type of mongoexport
You can't. If mongoexport exported 123 as 123.0, then 123 was a Double type in the document. You should try inserting the value as a 32- or 64-bit integer db.collection.insert({ "tweetId" : NumberLong(1234567) }) mongoexport exports JSON, using strict mode JSON representation, which inserts some type information into the JSON so MongoDB JSON parsers (like mongoimport) can reproduce the correct

Categories : Mongodb

Meteor collection limit
You could return an array of cursors by using the map function. Just stick your song query in your current map function. Instead of returning an id it would return the last three songs for the station with the given id. You could also convert this into an array of arrays or flatten it into a single array. You could then do a new query on the database for all songs whose id is in this array.

Categories : Mongodb

MongoDB Query: How to add some days to a date field before comparing it with a given date
You can't. A simple query in MongoDB can't use values from the document it's querying. You can only use values that are constant throughout the query. Valid Query: { FirstName : "bar" } Invalid Query: { FirstName : LastName } You can however acheive that by other means, for example MongoDB's aggregation framework

Categories : Mongodb

MongoDB elemMatch does not work expected
There is nothing wrong with the behavior of $elemMatch. It works as expected. The doc also says: However, the $elemMatch projection returns only the first matching element from the array. As a rule of thumb whenever you project an array using $elemMatch, only one of the elements will be projected at most. If none of the elements in the array match, the field won't be projected at all. So

Categories : Mongodb

MongoDB: calculate average value for the document & then do the same thing across entire collection
The way you aggregate has to be modified: Match the required region,sphere and where salary > 0. Project a extra field for each offer, which holds the average of start and end. Now group together the records with the same region and sphere, and apply the $avg aggregation operator on the avg_salary for each offer in that group,to get the average salary. The Code: db.offer.aggregate([ {

Categories : Mongodb

cannot authenticate hashed password in Flask
I believe the issue is that you are double-hashing the password when you instantiate the User object in your find_by_username method. That method grabs the info from the DB which would contain the hashed password. Then, it creates a User object with that data. The User object calls generate_password_hash during its __init__ method. So, the password is being double-hashed and therefore failing the

Categories : Mongodb

How to replicate a Python 2.7, Bottle, MongoDB OpenShift application locally in Linux Mint 17?
Directory Structure This is the structure of my app now that it is running locally: Environment Linux Mint 17 Cinnamon Steps To Replicate Locally 01) MongoDB 2.4.9 - DONE Install instructions for MongoDB 2.4.9 on Linux Mint 17: http://docs.mongodb.org/v2.4/tutorial/install-mongodb-on-ubuntu 02) RockMongo 1.1 (which requires Apache, PHP and MongoDB Driver) - DONE sudo apt-get install a

Categories : Mongodb

Reactivemongo TTL collections
I finally found it out. It's not really clear way to do it but seems to work: collection.indexesManager.ensure(Index(Seq(("Date", IndexType(BSONInteger(1)))), Some("expireAfterSeconds"), false, false, false, false, None, BSONDocument( "expireAfterSeconds" -> 0 ) This way every object with expireAfterSeconds: BSONDateTime in this collection will expire after the date specified But I don't eve

Categories : Mongodb

Accessing MongoDB from AppEngine app
It seems that you can't use direct MongoDB connection from appengine app due to the restricted nature of appengine sandbox. From https://cloud.google.com/appengine/docs/managed-vms/: Network Access: Only via App Engine services (includes outbound sockets) There are some possbilities to access MongoDB via HTTP REST interface, but it's not my case.

Categories : Mongodb

SyntaxError: Unexpected token ILLEGAL. Please help me insert syntax
You're using curly quotes. Only plain quotes work: db.tasks.insert({id : "0", title : "task01", description : "description", status : "1", assignorId : "7", assigneeId : "8", createdDate : "", startedDate : "", targetDate : "", completeDate : "", closedDate : ""})

Categories : Mongodb

Why can't I aggregate with MongoDB with a $match?
Put each pipeline stage into its own object within an array: db.essays.aggregate([ { $match: { essayId: 3 }}, { $group: { _id: { year: { $year: '$essayTime' }, month: { $month: '$essayTime' }, day: { $dayOfMonth: '$essayTime' } }, count: { $sum: 1 } }} ]);

Categories : Mongodb

Selecting MongoDB or DynamoDB pricing
Since This question remains unanswered possibly because the options are too costly. The best solution I found was AWS simpleDB which is a fraction of the cost. Both dynamodb and simpleDB do not conform to the ACID test so are unsuitable where consistency or security such as payments need conforming. Not to sound like I'm on an ACID trip, they both conform to the BASE principals (Basically avail

Categories : Mongodb

MongoDB: How to count a field if it's value matches a condition?
You can use query something similar to below. db.dbversitydotcom_col.aggregate([ { $unwind: “$log” }, { $match: { “log.type” : “clicked”, "log.utc_timestamp" : "your required date" } }, { $sort: { “Files.Size” : -1.0 } }, { $limit: 5.0 } ]).count() Please refer to http://dbversity.com/mongodb-importance-of-aggregation-framework/ for more detailed explanation,

Categories : Mongodb

failed login with correct credentials set in the admin db - MongoDb
Try using the --authenticationDatabase option : mongo localhost/cars --authenticationDatabase admin -u master -p

Categories : Mongodb

PyMongo query on Aggregation
The "pipeline" variable seems unnecessary. Without seeing your error, and assuming your connection to the database is fine This line: result = connect.aggregate(pipeline=pipe2) Should just be: result = connect.aggregate(pipe2) After duplicating your collection from the information given, this worked for me. Here's the full code (my connection looks a bit different than yours as well) Col

Categories : Mongodb

How can two keys be combined into one new object in Mongodb?
Sadly mongodb doesn't allow updates based off of fields in the document. https://jira.mongodb.org/browse/SERVER-458 You'll need to do this as two separate operations, one that finds documents to modify, and one that updates those documents with the correct new date.

Categories : Mongodb

3 conditions with and does not work
You have complicated the query with unnecessary DBObjects. The below code represents how to build the DBObject with a condition to match the documents with entity in 11 or 12, and time = 20141105230011. MongoClient mongoClient = new MongoClient("localhost", 27017); DB db = mongoClient.getDB("test"); DBCollection coll = db.getCollection("test"); DBObject inOp = new BasicDBObject()

Categories : Mongodb

How can I query mongodb for a list of credit cards that are about to expire?
Easiest way seems to be to join these two fields into a Date object, then run the below query. How to combine the two fields - answer here Meteor.publish('card_expiring', function () { var today = new Date(); var future_date = new Date(new Date(today).setMonth(today.getMonth()+3)); return Donate.find({'card.expires' : {$lte : future_date }}, { card : true } ); }); Of course this j

Categories : Mongodb

Update all documents in a collection with random numbers
You can make use of the cursor.forEach() cursor method in the mongo shell to achieve this: db.myDoc.find({rand: {$exists : false }}).forEach(function(mydoc) { db.myDoc.update({_id: mydoc._id}, {$set: {rand: Math.random()}}) })

Categories : Mongodb

Cannot apply the positional operator without a corresponding query field containing an array
You can make use of the cursor.forEach() cursor method in the mongo shell to achieve this: db.organizations.find({"name" : "Paul", "a.b" : {$exists: true}}).forEach(function(doc) { array = doc.a.b; array.forEach(function(elem) { elem.lastname="no_lastname" }); db.organizations.update({_id:doc._id}, {$set:{"a.b":array}}); })

Categories : Mongodb

MongoDB - Update or Create an object in nested Array in Pymongo
You almost there: db.YourCollection.update( { '_id':'50001', <-- to find document 'data.name': 'jango' < -- to find element of the array }, { '$set': { "data.$.grade" : 'A' } } <-- with .$ you reference array element from first argument ) Link to documentation

Categories : Mongodb

MongoDB - Sorting a query twice?
You could try: User.find().sort({score: -1, updatedAt: 1}).limit(10).exec(function(err, users) { }); This will sort by score descending, followed by updatedAt ascending. Mentioned here.

Categories : Mongodb

How to define write preferences without tag sets?
What you could do is to use something which is called "replication chaining". It basically works like this: You create (or reconfigure) your replica set with chaining allowed You tell R2 and R4 to replicate from R3 using replSetSyncFrom. Done! The syncing should look like this after following these steps: R1 └── R3 ├── R2 └── R4 The good: If R3 fails, R2 and

Categories : Mongodb

mongo document with only keys inside keys, how to do a find on key range
You can build your query in the following pattern. It is a native mongo driver javascript code, but on transformation to python should work correctly. var month = 11; var range = [20,21,22]; var year = 2014; var project = {}; var find = {}; range.forEach(function(i){ var str = year+"."+month+"."+i+"."+"Counts"+"."+"c"; find[str] ={"$exists":true}; project[str] = 1; }) db.collection.find(find,proj

Categories : Mongodb

where clause for array on mongo does not work
$in should be a BasicDBObject as well: DBObject oredrFields = new BasicDBObject(); DBObject inOp = new BasicDBObject(); inOp .put("$in", new String[]{"1","2"}); oredrFields.put("entity", inOp);

Categories : Mongodb

MongoDB MMS to monitor and backup existing mongo instance
As of the mid-October 2014 release of MMS, monitoring & backup has been integrated with deployment via the automation agent (http://blog.mongodb.org/post/99991498968/mongodb-management-service-re-imagined-the-easiest-way). There currently isn't an option to attach MMS to existing MongoDB deployments, however you can watch/upvote MMS-1991 in the MongoDB issue tracker for updates. Is there a

Categories : Mongodb

Query to retrieve multiple items in an array
You can't. MongoDB returns the document that matches the query conditions, not individual pieces that match the query conditions. You can suppress or include fields of the matching documents with projection, but you cannot (as of 2.6) return an array restricted just to contain elements that matched conditions on the array. You can return just the first such match with $ db.collection.find( {

Categories : Mongodb

How to setup a MongoDB with Vagrant and Docker
In order for servers to communicate I guess you would need to configure port forwarding properly, so that routing server would be able to access shards, and vice versa. With Vagrant one can configure port forwarding, and in this case, I suppose also needs to be combined with ports being properly configured for Docker containers. Refer to Vagrant Networking Configuration page and Vagrant's Docker

Categories : Mongodb

MongoDB simple geoWithin query takes 10 minutes on 3M documents
So, I'm answering my question even though I still don't know why it's slow. But I know the answer to my real question, which is "what should I do now?" The answer is, migrate to Postgres/PostGIS. Did some benchmarking: http://ilessendata.blogspot.com/2015/04/mongodb-vs-postgresql-for-geo-queries.html if you'd like to know more, but in short, it looks like geo "find everything within this box" qu

Categories : Mongodb

Using Alteryx's Mongo Connection Tool To Connect With A Mongo Labs Database (Collection)
Yes, I am using that MongoDB extractor on a daily basis to generate TDE files to feed Tableau, since Tableau does not offer dedicated extractors, but I admit it was difficult to get started. Extraction is now swift from a MongoDB running on AWS, make sure you indicate the proper collection, and be aware of one flaw with the current version of extractor, as of Alteryx 9.5: it is missing the flag to

Categories : Mongodb

mongodb grails simple application times out
I'm fairly certain the issue was on the mongod side. I stopped the mongo daemon, put it into high verbose debug mode (using mongod -vvvv command), and when I tried to replicate the issue while watching the console output, the issue did not happen. I'm not entirely sure what the exact cause of the timeout was, but its not happening now. Thanks for the responses.

Categories : Mongodb

Why can't I cabal install --only-dependencies with mongodb?
After looking here Cabal configure in a sandbox complains "At least the following dependencies are missing" on installed packages I saw that the answer states that package names are case sensitive. So I tried changing mongodb to the way MongoDB spells it, namely MongoDB. This did not work, so I tried changing it to mongoDB, and finally there was joy. So even though I can do cabal ins

Categories : Mongodb

how to understand read preferences in mongo
Yes Yes Yes, but the link that you provided is only for readPreference You also need to supply custom writeConcern (extract from link in a question): db.users.insert( { id: "xyz", status: "A" }, { writeConcern: { w: "MultipleDC" } } ) Look into php driver documentation how to do that. Yes, you may skip call to slaveOK in this case (especially, that in 95% cases you will be reading from prima

Categories : Mongodb


Recently Add
python pymongo match not working
Where will MongoDB "forEach" commands run?
MongoDB tag range not working
MongoDB - make replica set member passive without disconnecting clients?
Is it possible to ensure uniqueness on a sharded hashed key in MongoDB?
Spring Data (mongoDb) + @Id element + EJB + DBRef. Cannot create a reference to an object with a NULL id
Mongo Db optimized query
how to set the data type of mongoexport
Meteor collection limit
MongoDB Query: How to add some days to a date field before comparing it with a given date
MongoDB elemMatch does not work expected
MongoDB: calculate average value for the document & then do the same thing across entire collection
cannot authenticate hashed password in Flask
How to replicate a Python 2.7, Bottle, MongoDB OpenShift application locally in Linux Mint 17?
Reactivemongo TTL collections
Accessing MongoDB from AppEngine app
SyntaxError: Unexpected token ILLEGAL. Please help me insert syntax
Why can't I aggregate with MongoDB with a $match?
Selecting MongoDB or DynamoDB pricing
MongoDB: How to count a field if it's value matches a condition?
failed login with correct credentials set in the admin db - MongoDb
PyMongo query on Aggregation
How can two keys be combined into one new object in Mongodb?
3 conditions with and does not work
How can I query mongodb for a list of credit cards that are about to expire?
Update all documents in a collection with random numbers
Cannot apply the positional operator without a corresponding query field containing an array
MongoDB - Update or Create an object in nested Array in Pymongo
MongoDB - Sorting a query twice?
How to define write preferences without tag sets?
© Copyright 2017 spot7.org Publishing Limited. All rights reserved.