Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing MongoDB collection values in JavaScript

I am new in Meteor, and especially in MongoDB.

I have googled a lot regarding this issue but nothing found related to this.

So there is an app that contains two collections: EventsCollection and RacesCollection and runs on Meteor server.

The RacesCollection has number of records like:

RacesCollection.insert({raceId:"r1", eventId:"e1", raceName:"Moto race 1", status:"statusDetail", mode:"modeDetail"});
RacesCollection.insert({raceId:"r2", eventId:"e1", raceName:"Moto race 2", status:"statusDetail", mode:"modeDetail"});

This is the resultant collection which contains rows having eventId = e1

var race = RacesCollection.find({eventId: "e1"});

Now what i want to do is to simply access the fields of race into javascript, something like race.raceId, race.raceName. How to implement this? Is there any getter method for accessing particular data field?

And how to iterate through multiple rows of race in case it contains number of rows?

Any recommendation will be appriciated.

like image 261
sohel khalifa Avatar asked Oct 18 '12 13:10

sohel khalifa


People also ask

How to display all documents from a collection in MongoDB?

Display all documents from a collection with the help of find () method − Following is the query to access the array in a MongoDB collection and fetch a specific document −

How do I select a database in MongoDB?

A database stores one or more collections of documents. In MongoDB, databases hold one or more collections of documents. To select a database to use, in mongosh, issue the use <db> statement, as in the following example: If a database does not exist, MongoDB creates the database when you first store data for that database.

What is the difference between MongoDB and a database?

MongoDB stores data records as documents (specifically BSON documents) which are gathered together in collections. A database stores one or more collections of documents. In MongoDB, databases hold one or more collections of documents. To select a database to use, in mongosh, issue the use <db> statement, as in the following example:

How to get statistics of a MongoDB database using dbstats?

The dbstats method gets statistics of a database. The example connects to the testdb database and shows its statistics. This is a sample output. The find function creates a cursor for a query that can be used to iterate over results from MongoDB. In the example, we retrieve all docs from cars collection.


1 Answers

use ForEach :

db.databaseName.find(
  {
    field:"valueofField"
  }
).forEach(function(obj){
    print(obj.fieldname)
})
like image 138
Aysennoussi Avatar answered Sep 17 '22 17:09

Aysennoussi