0

I'm used to working with firebase where I can access a document directly by fetching data from the db like so.

db.collection('collectionName/documentID').get();

I can't seem to find any documentation regarding doing something similar in mongodb. Do I have to use a find query to grab data from a mongodb or have I missed something? Thanks

juicy89
  • 448
  • 5
  • 14

3 Answers3

0

I'm thinking

const collection = db.collection('collectionName');
collection.findOne({_id: ObjectId('documentID'); });
cross19xx
  • 3,170
  • 1
  • 25
  • 40
  • So with this method, I still need to perform a query on the db. Is there any way I can just access it directly as I know the id of the object I'm looking for? – juicy89 Feb 13 '19 at 15:28
  • @juicy89, do you mean the way Firebase does querying? If so, I'm sorry but I have no way of doing that. But I'll keep track of this post to get an answer if provided – cross19xx Feb 13 '19 at 15:29
0

In the mongo shell you can directly get it as below:

db.st4.find({"_id" : "1234"})

Result set:

{ "_id" : "1234", "raw" : { "meas" : { "meas1" : { "data" : "blabla" }, "mesa2" : { "data" : "foo" } } } }

Or by default mongo id as:

db.st1.find({"_id" : ObjectId("5c578d57ce9ba4a066ca2fa4")})

{ "_id" : ObjectId("5c578d57ce9ba4a066ca2fa4"), "name" : "Just a name", "users" : [ "user1", "user2" ] }

For display the result in pretty format

db.st1.find({"_id" : ObjectId("5c578d57ce9ba4a066ca2fa4")}).pretty()

Result set:

{
    "_id" : ObjectId("5c578d57ce9ba4a066ca2fa4"),
    "name" : "Just a name",
    "users" : [
        "user1",
        "user2"
    ]
}

Here st4 is my collection name in the database test, so once you are on mongo shell do the below steps before above query:

use test
db.st1.insert({"name" : "Just a name", "users" : [ "user1", "user2" ] })

and then you can query by default _id generated mongo, you can simply make a query to get the recently added documents in the collection st1 as below:

db.st1.find().sort({_id:-1}).limit(1)

Hope this will help you out to do some basic query on mongo shell

krishna Prasad
  • 3,541
  • 1
  • 34
  • 44
0

Since mongo consolse is an interactive javascript shell, One way would be to create a method similar to this:

function collectionNameGet(idToFind) {
  return db.collection.find({_id: idToFind });
}
Anirudh Bagri
  • 2,346
  • 1
  • 21
  • 33