Reputation: 137
I have a collection in my database called example that looks like this:
{
"event" : "cheat",
"message" : {
"tableid" : 398,
"time" : 1381853438870,
"link" : "/dbcheat/table398/iID485"
},
"_id" : ObjectId("525d68fe99ddc6a019000008")
}
There are thousands of records like this and I would like to look for the first 50 for instance.
I researched that the best way to go through this would be to use the forEach() function. I am used to SQL and just started with Mongo and understand that objectID is unique but I cant get an order from it.
var cursor = db.example.find();
cursor.forEach(function(x){
console.log(x.message);
});
But I am getting an error because for some reason because x is always null.
Any idea what could be wrong?
Upvotes: 0
Views: 3053
Reputation: 3157
you must add a handler in the find() for function( error, cursor ) and within that cursor, assuming error is null and cursor exists, then you do cursor.toArray( function( error, data ) )
In the first one, you have to wait for the data to come and expect an error. In the second one, the cursor will be turned into an usable array of jsons :> which is what you needed.
db.example.find( function( error, cursor)
{
if( error || !cursor)
{
console.log("error getting items");
}
else
{
cursor.toArray( function( error, items)
{
if( error || !items)
{
console.log("error getting items");
}
else
{
console.log( JSON.stringify( items ) );
}
});
});
}
Upvotes: 1
Reputation: 2520
To print the first X number you could just use a pattern like :
db.example.find().limit(x);
Where x is an integer specifying the first x
elements of the collection
If you want to get them all just use
db.example.find()
While if you want to skip the first y
elements and print the next x
use something like
db.example.skip(y).limit(x);
Also to have some sorting you could use the time field for that.
Upvotes: 0
Reputation: 3760
To look at the "first 50" you might want to sort the documents by time and limit the query result to the first 50 initially.
db.coll.find().sort({"message.time":1}).limit(50)
You could then use the toArray() method on the cursor and access the documents within that array.
Upvotes: 0