mongo_shell()

Read(292) Label: query, mongodb database, result,

Description:
 
Query the databsase and return the query result.

Syntax:
   mongo_shell(fd,s)

Note:

The function executes aMongoDB shell command s and returns the result. So far functions supported by s are find, count, distinct and aggregate.
Options:

@x

Close the MongoDB connection automatically closes when the execution finishes; if the returned result is a cursor, disconnect from the database as the cursor closes.

Parameters:

fd

MongoDB connection object

s 

An MongoDB function, which supports find, count, distinct and aggregate and follows the MongoDB syntax

Return value:
 
A sequence/table sequence/cursor

Example:

 

A

 

1

=mongo_open("mongodb://localhost:27017/mydb")

Conncet to database mydb on MongoDB server

2

=mongo_shell(A1,"emp.find()").fetch()

Query records of the emp set in database mydb

3

=mongo_shell(A1,"emp.find({GENDER:\"F\"})")

Query records where GENDER is F and return result as a cursor

4

=A3.fetch()

5

=mongo_shell@x(A1,"emp.count()")

Use @x option to query the number of records, and close the connection after result is returned

6

=mongo_open("mongodb://localhost:27017/mydb")

Connect to the MongoDB database

7

=mongo_shell(A6,"emp.aggregate([{$group : {_id : \"$GENDER\", number : {$sum : 1}}}])")

Count records by gender

8

=mongo_shell(A6,"emp.distinct(DEPT)")

Query DEPT in the emp set to remove duplicate values

9

=mongo_close(A6)

Close the database connection