I want to print the value for this JSON document in the mongo shell. Like a simple console output, without creating a new collection or document.
Thanks in advance
I found a solution, by using .forEach() to apply a JavaScript method:
db.widget.find(
{ id : "4" },
{quality_level: 1, _id:0}
).forEach(function(x) {
print(x.quality_level);
});
db.collection.find() returns a cursor.
There are a bunch of methods for the cursor object which can be used to get the cursor information, iterate, get and work with the individual documents from the query result (in the Mongo Shell). For example,
let result = db.widget.find( { id : "4" }, { quality_level: 1, _id: 0 } );
The methods print, printjson and tojson are useful for printing the query results assigned to a cursor and iterated over it, in the Mongo Shell.
In this particular example, each of the following statements will print the expected output:
result.forEach( doc => print( doc.quality_level ) );
result.forEach( doc => print( tojson(doc)) );
result.forEach( printjson );
Note the query must be run each time the cursor is to be iterated, as the cursor gets closed after iterating thru it. But, one can use the cursor.toArray() method to get a JavaScript array, and iterate the array and work with the query result documents without running the query again.
NOTES:
The db.collection.findOne() method returns a document (not a cursor).
Iterate a Cursor in the mongo Shell
Mongo Shell cursor methods
To print each document when returning a cursor:
db.widget.find().forEach(printjson);
db.widget.findOne({"id":4},{quality_level:1,_id:0}).quality_level
The projection is not necessary for this to work, but it reduces the data which is to be transferred in case of a sharded collection.
Related
Sorry if this is such a basic question but I can't seem to find an example of how to do this anywhere. I want to write a shell script that constructs a document from a find and insert the results into another collection...something like the following, but the following doesn't work:
cursor = db.Patients.find({},{"patient_id":1})
while (cursor.hasNext()) {
db.newCollection.insertOne(cursor.next());
}
When I run this, nothing is populated to the newCollection collection, but I don't get errors either.
Your code will work if you declare cursor as a variable to keep the shell from iterating over the cursor for you:
var cursor = db.Patients.find({},{"patient_id":1})
while (cursor.hasNext()) {
db.newCollection.insertOne(cursor.next());
}
But you may also want to have new _id values assigned to the inserted docs, so you can exclude the original _id values from the docs as:
var cursor = db.Patients.find({},{"patient_id":1, _id:0})
while (cursor.hasNext()) {
db.newCollection.insertOne(cursor.next());
}
Use $out operator in aggregation framework.
Try this mongo query:
db.Patients.aggregate([
{$project:{"patient_id":1}},
{$out: "NewCollection"}
])
Or use db.eval()
db.eval(function(patient_id){
var docs = db.Patients.find( { patient_id: patient_id } ).toArray();
db.NewCollection.insert(docs);
return docs;
}, 1);
Or use forEach()
db.Patients.find({"patient_id":1}).forEach(
function(doc){db.Newcollection.insert(doc);}
)
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 am trying get a list of people with the most entries in my database.
print db.points.aggregate(
[
{
"$group":
{
"_id": "$created.user",
"count":{"$sum":1}
}
},
{
"$sort":
{"count":-1}
}
]
)
An entry looks like this :
{
u'id': u'342902',
u'_id': ObjectId('555af76a029d3b1b0ff9a4be'),
u'type': u'node',
u'pos': [48.9979746, 8.3719741],
u'created': {
u'changeset': u'7105928',
u'version': u'4',
u'uid': u'163673',
u'timestamp': u'2011-01-27T18:05:54Z',
u'user': u'Free_Jan'
}
}
I know that created.user exists and is otherwise accessible.
Still the output i get is:
<pymongo.command_cursor.CommandCursor object at 0x02ADD6B0>
Shouldn't I get a sorted list ?
The result of an aggregation query is a cursor, as for a regular find query. In case of pymongo the CommandCursor is iterable, thus you are able to do any of the following:
cursor = db.points.aggregate(...)
# Option 1
print(list(cursor))
# Option 2
for document in cursor:
print(document)
Note: as arun noticed, in both cases, i.e. after you create a list out of the cursor, or iterate in the for loop, you will not be able to re-iterate over the cursor. In that case the first option becomes better, if you want to use it in future, as you can use the obtained list as much as you want, because it is in the memory already.
The reason of not being able to reiterate is that the cursor is actually on the server, and it send the data chunk-by-chunk, and after it has sent you all the data (or the server terminates) the cursor gets destroyed.
In mongo I have a collections with records. These record are very complex. Now I would like to duplicate one of them.
I can easily select the one
mongo> var row = db.barfoo.find({"name":"bar"});
Now I actually don't know what to do. I don't know what is in row because I cannot find a way to print its content. How can I change specific properties and finally insert this modified row again
mongo> db.barfoo.insert(row);
thnx
You must change value _id - generate new:
var row = db.barfoo.findOne({"name":"bar"});
row._id = ObjectId();
db.barfoo.insert(row);
Good Luck!
I am going to assume that you're working directly inside the mongo shell.
Once you have your document (not a row :P ), you'd modify the properties in the same way you would a normal JavaScript object:
var doc = db.barfoo.findOne( { "name": "bar" } );
doc.name = "Mr Bar";
Note that the find() command returns a cursor, so if you're looking to extract a single document, you should use the findOne() function. This function returns a single document.
If you are interested in duplicating numerous documents, you can use the find() function and iterate over the cursor to retrieve each document:
db.barfoo.find( { "name": "bar" } ).forEach( function( doc ){
doc.name = "Mr Bar";
}
After you change the relevant properties, you can use the insert/save methods to persist the data back to mongo. Don't forget to change/delete the _id attribute so that you'll actually create a new document.
As a side note, in order to view the contents of an object in the mongo shell, you can use the print() function. If you want a more visually appealing output, you could use printjson().
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