MongoDB - Mongo Shell and Java Script

Let us understand the details about JavaScript interpreter that comes as part of Mongo CLI.

  • Mongo also have JavaScript interpreter
  • We can develop standalone JavaScript code and execute using mongo
  • It is primarily used for reconciliation of data, creating new data sets from existing data etc.
  • We can write JavaScript code as part of Mongo Shell. It executes synchronously.
  • We cannot use this approach of reconciliation in Node as Node executes asynchronously. We have to write code a bit differently to achieve this using NodeJS.
  • Let us come up with code which will create new collection orderDetails . This collection will have orders with order_id, order_date, order_customer_id and order_status along with additional field called as order_item_details.
  • order_item_details is nothing but a list of items from orderItems.
  • Here are the steps to develop this task using JavaScript
    • Create Connection
    • Create a Database object
    • Create collection objects for both orders and orderItems
    • Execute Query and Iterate through cursor (for orders data set)
    • Lookup into orderItems using order_id and build a list (order_item_details)
    • Add order_item_details to orders and then insert into the orderDetails collection.
  • We can also achieve it using an aggregate function called $lookup .