Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a specific key-value pair from mongodb collection

If I have a mongodb collection users like this:

{
  "_id": 1,
  "name": {
    "first" : "John",
    "last" :"Backus"
  },
}

How do I retrieve name.first from this without providing _id or any other reference. Also, is it possible that pulling just the `name^ can give me the array of embedded keys (first and last in this case)? How can that be done?

db.users.find({"name.first"}) didn't work for me, I got a:

SyntaxError "missing: after property id (shell):1

like image 646
Swapnil Avatar asked Dec 18 '12 06:12

Swapnil


People also ask

How do I find a specific value in MongoDB?

Find() Method. In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents. Cursor means a pointer that points to a document, when we use find() method it returns a pointer on the selected documents and returns one by one.

How retrieve data from collections in MongoDB?

You can use read operations to retrieve data from your MongoDB database. There are multiple types of read operations that access the data in different ways. If you want to request results based on a set of criteria from the existing set of data, you can use a find operation such as the find() or findOne() methods.

Is MongoDB a key-value pair?

MongoDB covers a wide range of database examples and use cases, supporting key-value pair data concepts. With its flexible schema and rich query language with secondary indexes, MongoDB is a compelling store for “key-value” data.

How do I use FindAndModify in MongoDB?

MongoDB – FindAndModify() Method. The findAndModify() method modifies and return a single document that matches the given criteria. By default, this method returns a pre-modification document. To return the document with the modifications made on the update, use the new option and set its value to true.


1 Answers

The first argument to find() is the query criteria whereas the second argument to the find() method is a projection, and it takes the form of a document with a list of fields for inclusion or exclusion from the result set. You can either specify the fields to include (e.g. { field: 1 }) or specify the fields to exclude (e.g. { field: 0 }). The _id field is implicitly included, unless explicitly excluded.

In your case, db.users.find({name.first}) will give an error as it is expected to be a search criteria.

To get the name json : db.users.find({},{name:1})

If you want to fetch only name.first

db.users.find({},{"name.first":1})

Mongodb Documentation link here

like image 84
Rahul Avatar answered Oct 11 '22 20:10

Rahul