I'm getting a strange result when trying to use eval with the args argument. The following works fine:
> db.eval(function(coll) {
var res = db[coll].find({});
return(res.count());
}, ['KenColl'])
1438
But when I pass a second argument, I always get empty results, even if I don't use it:
> db.eval(function(coll, query) {
var res = db[coll].find({});
return(res.count());
}, ['KenColl', {}])
0
Am I misunderstanding something about eval and args? I'm running version 2.4.3 of both mongod and the MongoDB shell.
For db.eval you shouldn't pass the arguments as an array, just pass them into the function.
The following example should work:
db.eval(function(coll, query) {
var res = db[coll].find(query);
return(res.count());
}, 'KenColl', {})
p.s. your first example only works because in javascript db['KenColl'] === db[['KenColl']]
Related
I'd like to define a custom Mongo shell command. Given .mongorc.js is like below:
var dbuc;
(function () {
dbuc = (function () {
return db.getName().toUpperCase();
})();
})();
I'm getting proper upper-cased name for initial database, yet when I switch to other database I'm still getting name of the initial database instead of current one.
> db
test
> dbuc
TEST
> use otherbase
> db
otherbase
> dbuc
TEST
I see .mongorc.js is run before mongo runs and that's why dbuc variable has assigned value of initial database - test. But I rather wonder how to get a name of current database whatever base I turned on.
There are a few things to note:
In mongo shell, typeof db is a javascript object and typeof dbuc is string.
I believe, in your code, dbuc value is assigned once and does not change when use is called.
use is a shellHelper function(type shellHelper.use in mongo shell). It reassigns variable db with newly returned database object.
One of the solutions, for dbuc to work, is to add following code to .mongorc.js
// The first time mongo shell loads, assign the value of dbuc.
dbuc = db.getName().toUpperCase();
shellHelper.use = function (dbname) {
var s = "" + dbname;
if (s == "") {
print("bad use parameter");
return;
}
db = db.getMongo().getDB(dbname);
// After new assignment, extract and assign upper case
// of newly assgined db name to dbuc.
dbuc = db.getName().toUpperCase();
print("switched to db " + db.getName());
};
I want to write functions into MongoDB Shell like this:
var last = function(collection) { db[collection].find().sort({_id: -1}).limit(1).toArray(); }
But there is one problem. When I call last() function, it will make no output. How to fix it?
You need to use either use the JavaScript print() function or the mongo specific printjson() function which returns formatted JSON to actually log to output the result from the find method, for example:
var last = function(collection) {
var doc = db.getCollection(collection).find().sort({_id: -1}).limit(1).toArray();
printjson(doc);
};
last("test");
I am using gulp and gulp-shell packages for a php Laravel application, I just need to know if this is possible to pass argument from cmd to gulpfile.js ? this is my file:
gulp.task('default', shell.task([
'echo user',
]));
Question:
Is it possible to pass an argument from command-line when running gulp and then inside the gulpfile print it out instead of user?
var command_line_args = require('yargs').argv
Not sure if this is of any use to you or others but I did this manually by passing the arguments explicitly through a custom function. It's not super elegant but it gets the job done.
var appendWithCommandLineArguments = function(cmd, arguments) {
var to_append = _.chain(command_line_args)
.pick(arguments)
.reduce(function(string, val, prop){
return string+"--"+prop+"="+val+" ";
}, " ")
.value();
return cmd + to_append
}
gulp.task('taskmailer', shell.task([
appendWithCommandLineArguments('node automate/build/mail/taskMailer.js', ["email", "template"])
]))
I am working with mongo client. Sometimes the output of some commands I execute involve an enormous output, which mongo prints on screen. How can I avoid this?
There is a way to suppress output.
Using "var x = ...;" allows to hide output of expressions.
But there are other commands that harder to suppress like
Array.prototype.distinct = function() {
return [];
}
This produces printing of new defined function.
To suppress it you will need to write it in this way:
var suppressOutput = (
Array.prototype.distinct = function() {
return [];
}
);
Per the comment by #WiredPrairie, this solution worked for me:
Just set the return value to a local variable: var x=db.so.find(); and inspect it as needed.
Trying to learn the Meteor framework as well as coffeescript/node all at once. Been working on a simple file upload program that utilizes onloadend. When the FileReader onloadend event function is called I try to determine if the file already exists and if so I update with the new file data and version.
The code works for insert but not update. Can someone help? I've posted to meteor-talk w/o an answer as I suspect its the weekend (when I do most of my experimentation).
Code snippet...
file_reader.onloadend = ((file_event) ->
(event) ->
f_filename = escape file_event.name
version = 0
f_record = null
f_record = doc_repo.findOne { name: f_filename }
if f_record && f_record.name
doc_repo.update
name: f_filename
,
$set:
version: 10
else
doc_repo.insert
name: f_filename
data: event.target.result
version: 0
)(file_obj)
Error
Exception while invoking method '/documents/update' TypeError: Cannot read property 'toBSON' of undefined
at Function.calculateObjectSize (/usr/local/meteor/lib/node_modules/mongodb/node_modules/bson/lib/bson/bson.js:210:12)
at BSON.calculateObjectSize (/usr/local/meteor/lib/node_modules/mongodb/node_modules/bson/lib/bson/bson.js:1463:15)
at UpdateCommand.toBinary (/usr/local/meteor/lib/node_modules/mongodb/lib/mongodb/commands/update_command.js:67:20)
at Connection.write (/usr/local/meteor/lib/node_modules/mongodb/lib/mongodb/connection/connection.js:138:40)
at __executeInsertCommand (/usr/local/meteor/lib/node_modules/mongodb/lib/mongodb/db.js:1837:14)
at Db._executeInsertCommand (/usr/local/meteor/lib/node_modules/mongodb/lib/mongodb/db.js:1912:7)
at Collection.update (/usr/local/meteor/lib/node_modules/mongodb/lib/mongodb/collection.js:445:13)
at app/packages/mongo-livedata/mongo_driver.js:178:16
at Db.collection (/usr/local/meteor/lib/node_modules/mongodb/lib/mongodb/db.js:507:44)
at _Mongo._withCollection (app/packages/mongo-livedata/mongo_driver.js:51:13)
It looks like Mongo is not getting the second parameter which it needs to do the update. So in regular JavaScript it's expecting this:
collection.update({..selector..}, { .. modifier });
So I'd try putting some curly brackets around the modifier object, like this:
doc_repo.update
name: f_filename,
{
$set:
version: 10
}