Querying/Finding/Selecting Dcouments in MongoDB

>_ Finding The Document

  • MongoDB provides db.collection.find() method to read documents from a collection.

    Syntax:-
    db.collection.find(query, projection)
    Parameter Type Description
    query document Optional. Specifies selection filter using query operators. To return all documents in a collection, omit this parameter or pass an empty document ({}).
    projection document Optional. The projection parameter determines which fields are returned in the matching documents. { field1: 1or0, field2: 1or0 ... }

    Note:- Please refer WildCard/RegEx section in this tutorial for better query making

    Example:-

    >_ List all entries of ‘users’ collection

    >db.users.find()

    Output:-

    {"_id" :ObjectId("5774adbcfc520de27ab8744e"),"userid" : "Alex",
    "Age" : 25,"gamesplayed" : ["Rummy","TeenPati"]} { "_id" :ObjectId("5774ae18fc520de27ab8744f"), "userid" : "Andrew",
    "Age" : 40, "gamesplayed" : [ ], "totalbet" : 0,"totalwin" :0}

    >_ List userids from ‘users’ collection

    >db.users.find({},{userid:1}).pretty()

    Output:-

     {"_id" : ObjectId("5774adbcfc520de27ab8744e"),
     "userid" : "Alex"}
     {"_id" : ObjectId("5774ae18fc520de27ab8744f"),
     "userid" : "Andrew"}
      
Copyright © 2018-2020 TutorialToUs. All rights reserved.