I'm using the mongodb native driver v3.2.3 and trying to query how many collections are in the current database. I thought it would be
db.listCollections()
But this does not appear to return a count.
You can get the collection count of a database via the stats method:
let stats = await db.stats();
console.log(stats.collections);
That function returns a cursor which you can then use 'forEach()' on. Like this:
db.listCollections({}, {nameOnly: true}).forEach((_col) => {
console.log(_col.name)
})
You will then have to increment a counter for each collection, or push each collection name to an array and then check it's length.
Another way to get the collection count quickly would be to use the 'collections()' function like this:
db.collections({}, (error, collections) => {
console.log(collections.length)
})
listCollections source
collections source
Related
Selecting specific item from returned query (newbie)
Using laravel with the https://github.com/jenssegers/laravel-mongodb#query-builder package so the php is a bit off the norm for MongoDB terminology
I query the database like so:
$role_id = Role::where('name', 'Admin')->get();
How do I access the '_id' of the returned query?
I would like to grab the '_id' in a variable
get() returns Illuminate\Support\Collection object. That means you are getting an array of return items. So, in your case, you should iterate $role_id to loop through the items and get _id. Like this -
foreach ($rid as $role_id) {
echo $rid->_id;
}
Why dosen't db.find work? The console.log gets undefined...
var course = (db.courses.find({ _id: mongo.helper.toObjectID(param.course)}));
console.log(course.body)
The way you are trying use Selects documents in a collection and returns a cursor to the selected documents., so you can't use the way you are trying to use it.
You need to use a callback() to get the records matching the query.
The below code will give result in an array format :-
db.courses.findOne({ _id: mongo.helper.toObjectID(param.course)}).toArray(function(err, result)
{
console.log(result[0]); // will give you the matched record.
})
I'm new to Mongo, and I'm trying to retrieve the first document from a find() query:
> db.scores.save({a: 99});
> var collection = db.scores.find();
[
{ "a" : 99, "_id" : { "$oid" : "51a91ff3cc93742c1607ce28" } }
]
> var document = collection[0];
JS Error: result is undefined
This is a little weird, since a collection looks a lot like an array. I'm aware of retrieving a single document using findOne(), but is it possible to pull one out of a collection?
The find method returns a cursor. This works like an iterator in the result set. If you have too many results and try to display them all in the screen, the shell will display only the first 20 and the cursor will now point to the 20th result of the result set. If you type it the next 20 results will be displayed and so on.
In your example I think that you have hidden from us one line in the shell.
This command
> var collection = db.scores.find();
will just assign the result to the collection variable and will not print anything in the screen. So, that makes me believe that you have also run:
> collection
Now, what is really happening. If you indeed have used the above command to display the content of the collection, then the cursor will have reached the end of the result set (since you have only one document in your collection) and it will automatically close. That's why you get back the error.
There is nothing wrong with your syntax. You can use it any time you want. Just make sure that your cursor is still open and has results. You can use the collection.hasNext() method for that.
Is that the Mongo shell? What version? When I try the commands you type, I don't get any extra output:
MongoDB shell version: 2.4.3
connecting to: test
> db.scores.save({a: 99});
> var collection = db.scores.find();
> var document = collection[0];
In the Mongo shell, find() returns a cursor, not an array. In the docs you can see the methods you can call on a cursor.
findOne() returns a single document and should work for what you're trying to accomplish.
So you can have several options.
Using Java as the language, but one option is to get a db cursor and iterate over the elements that are returned. Or just simply grab the first one and run.
DBCursor cursor = db.getCollection(COLLECTION_NAME).find();
List<DOCUMENT_TYPE> retVal = new ArrayList<DOCUMENT_TYPE>(cursor.count());
while (cursor.hasNext()) {
retVal.add(cursor.next());
}
return retVal;
If you're looking for a particular object within the document, you can write a query and search all the documents for it. You can use the findOne method or simply find and get a list of objects matching your query. See below:
DBObject query = new BasicDBObject();
query.put(SOME_ID, ID);
DBObject result = db.getCollection(COLLECTION_NAME).findOne(query) // for a single object
DBCursor cursor = db.getCollection(COLLECTION_NAME).find(query) // for a cursor of multiple objects
I'm having an issue trying to sort after a map reduce. The collection has statistics (like scores) with users attached, so it's finding the highest score of the user. That portion works, the sort is to then sort those results for a leaderboard. I've put these functions into javascript variables and run them in the mongo console and a simple find().sort({'value.max.value':-1}) works fine on the resulting collection but I can't get it to work here. (My results come back unordered).
$query->map('function() {
var x = { value : parseInt(this.value), _id : this._id, date : this.postDate };
emit(this.user, { max : x });
}')
->reduce('function(key, vals) {
var res = vals[0];
for (var i=1; i<vals.length; i++)
{
if(vals[i].max.value > res.max.value)
res.max = vals[i].max;
}
return res;
}')
->sort('value.max.value', 'desc');
When you do a ->map or ->reduce call, Doctrine internally switch the "query mode" from "find" mode to "mapreduce" mode.
So you are actually doing a mapReduce MongoDB command as in the MongoDB Documentation
This means that your sort() call is translated to a sort property in the mapReduce command, and so it sorts only the input documents.
To actually sort the output you have 2 options:
Use the out() method in the query to output the results to a temporary Collection, then query the data from there with sort
Sort the results in php
The sort of a map-reduce is applied to the input documents (as fed to map), not the result. If you want to sort the results of the map-reduce you'd need to output to a collection and then perform a sorted find query on that collection (as you've successfully tried).
Short Version: I basically want to do what show collections does in the mongo shell, in mongoose.
Long Version:
I want to create an application that allows users to basically create their own Schema's > Collections > Documents using mongo + mongoose + node.js.
The first step of this application would be to show previously created Collections and their Documents. But since these would be created by a user their names are not known.
The code I've found that came closest was:
function find (collec, query, callback) {
mongoose.connection.db.collection(collec, function (err, collection) {
collection.find(query).toArray(callback);
});
}
But I don't know what the name of the collection is so I can't pass the 'collec' parameter.
So, anyone know how to get the list of collections without knowing their names?
I ended up using node-mongodb-native (the mongo driver that mongoose works on top of) to get the collection names:
var nmn_connect = require('mongoose/node_modules/mongodb').connect;
nmn_connect('mongo://localhost:27017/DATABASE', function(err, db) {
if(!err){
db.collectionNames(function(err, names){ // what I was looking for
if(!err){
console.log(names);
db.close();
}else{
console.log(err);
db.close();
}
});
}else{
console.log(err)
}
});
The Object returned by mongoose.connect() has no method similar to collectionNames() that I can find.
I know nothing of mongoose, but this page suggests that you could use mongoose.connection.collections to access all collections: http://mongoosejs.com/docs/api.html
each collection again should have a name attribute.
try this:
mongoose.connection.db.collectionNames(function (err, names) {
});