MonogDB – Documents

MongoDB stores data records as BSON documents. BSON is a binary representation of JSON documents, though it contains more data types than JSON.
BSON data types

var mydoc = {
               _id: ObjectId("5099803df3f4948bd2f98391"),
               name: { first: "Alan", last: "Turing" },
               birth: new Date('Jun 23, 1912'),
               death: new Date('Jun 07, 1954'),
               contribs: [ "Turing machine", "Turing test", "Turingery" ],
               views : NumberLong(1250000)
            }

Dot Notation

MongoDB uses the dot notation to access the elements of an array and to access the fields of an embedded document.

For examples querying arrays, see:
1. Query an Array
2. Query an Array of Embedded Documents
SEE ALSO

For examples querying embedded documents, see:
1. Query on Embedded/Nested Documents
2. Query an Array of Embedded Documents

Document Structure Operations

1. Query Filter Documents :

You can use : expressions to specify the equality condition and query operator expressions.

{
  <field1>: <value1>,
<field2>: { <operator>: <value> },
  ...
}

For examples, see:
1.Query Documents
2.Query on Embedded/Nested Documents
3.Query an Array
4.Query an Array of Embedded Documents

2. Update Specification Documents

Update specification documents use update operators to specify the data modifications to perform on specific fields during an db.collection.update() operation.

{
  <operator1>: { <field1>: <value1>, ... },
  <operator2>: { <field2>: <value2>, ... },
  ...
}

For examples, see Update specifications.

3. Index Specification Documents

Index specification documents define the field to index and the index type:

{ <field1>: <type1>, <field2>: <type2>, ...  }

Operators


1. Query and Projection Operators
2. Update Operators
3. Aggregation Pipeline Stages
4. Aggregation Pipeline Operators
5. Query Modifiers

1.Query- Array

Query Filter

{
	...
	<field1> : <value1>,
	<field2> : { <operator : <value>},
	....
}

1. Exact Array (order match) : []
2. Contains Array : {tags: [$all: [‘red’, ‘blank’]]}
3. Query An Array / On Field / Equality Match : {tags: ‘red’}
all document where tags is an array that contains the string “red” as one of its element

4. With Operator : {dicm: {$gt: 25}}
any contains at least one element where value is greater than 25

5. Compound Filter conditions : {dicm: {$gt:15, $lt: 20 }}
one element can stisfy the greater than 15 & another element can satisfy the less than 20

6. Meets Multiple Criteria : {dim: { $elementMatch : {$gt: 22, $lt: 30} } }
$elementMatch – at least one element satisfies all the specified criteria

2. Query on Embedded / Nested Documents

1. Match : size: { h: 14, w: 21, uom: ‘cm’ }
2. Query on Nested Field / Equality Match : { ‘size.uom’: ‘in’ }
3. Match using Query Operator : { ‘size.h’: { $lt: 15 } }
4. AND Condition :
{
‘size.h’: { $lt: 15 },
‘size.uom’: ‘in’,
status: ‘D’
}

3.Query an Array of Embedded Documents

1. Query for a Document Nested in an Array (Exact Match) :
instock: { warehouse: ‘A’, qty: 5 }

2. Specify a Query Condition on a Field in an Array of Documents :
‘instock.qty’: { $lte: 20 }

3.Use the Array Index to Query for a Field in the Embedded Document :
‘instock.0.qty’: { $lte: 20 }

4. A Single Nested Document Meets Multiple Query Conditions on Nested Fields :
instock: { $elemMatch: { qty: 5, warehouse: ‘A’ } }
instock: { $elemMatch: { qty: { $gt: 10, $lte: 20 } } }

5. Combination of Elements Satisfies the Criteria
For example 1 , the following query matches documents where any document nested in the instock array has the qty field greater than 10 and any document (but not necessarily the same embedded document) in the array has the qty field less than or equal to 20:

instock: { $elemMatch: { qty: { $gt: 10, $lte: 20 } } }

The following example 2 : queries for documents where the instock array has at least one embedded document that contains the field qty equal to 5 and at least one embedded document (but not necessarily the same embedded document) that contains the field warehouse equal to A:
{
‘instock.qty’: 5,
‘instock.warehouse’: ‘A’
}

Operators

1. $push

The $push operator appends a specified value to an array.

{ $push: { <field1>: <value1>, ... } }

If the value is an array, $push appends the whole array as a single element. To add each element of the value separately, use the $each modifier with $push.

When used with modifiers, the $push operator has the form:

{ $push: { <field1>: { <modifier1>: <value1>, ... }, ... } }

The processing of the push operation with modifiers occur in the following order, regardless of the order in which the modifiers appear:
1.Update array to add elements in the correct position.
2.Apply sort, if specified.
3.Slice the array, if specified.
4.Store the array.

Examples

1. Append a Value to an Array

db.students.update(
   { _id: 1 },
   { $push: { scores: 89 } }
)

2. Append Multiple Values to an Array

db.students.update(
   { name: "joe" },
   { $push: { scores: { $each: [ 90, 92, 85 ] } } }
)

3.Use $push Operator with Multiple Modifiers :

db.students.update(
   { _id: 5 },
   {
     $push: {
       quizzes: {
          $each: [ { wk: 5, score: 8 }, { wk: 6, score: 7 }, { wk: 7, score: 6 } ],
          $sort: { score: -1 },
          $slice: 3
       }
     }
   }
)

2.$pull

The $pull operator has the form:

{ $pull: { <field1>: <value|condition>, <field2>: <value|condition>, ... } }

Behavior

a. If you specify a and the array elements are embedded documents, $pull operator applies the as if each array element were a document in a collection.
1. Remove Items from an Array of Documents

db.survey.update(
  { },
  { $pull: { results: { score: 8 , item: "B" } } },
  { multi: true }
)

The $pull expression applies the condition to each element of the results array as though it were a top-level document.

b. If the specified <value> to remove is an “array”, $pull removes only the elements in the array that match the specified exactly, including order.

c.If the specified <value> to remove is a “document”, $pull removes only the elements in the array that have the exact same fields and values. The ordering of the fields can differ.

2.Remove All Items That Equal a Specified Value

db.stores.update(
    { },
    { $pull: { fruits: { $in: [ "apples", "oranges" ] }, vegetables: "carrots" } },
    { multi: true }
)

3.Remove All Items That Match a Specified $pull Condition

db.profiles.update( { _id: 1 }, { $pull: { votes: { $gte: 6 } } } )

3. Where the an array (results) contains embedded documents that also contain arrays:

{
   _id: 1,
   results: [
      { item: "A", score: 5, answers: [ { q: 1, a: 4 }, { q: 2, a: 6 } ] },
      { item: "B", score: 8, answers: [ { q: 1, a: 8 }, { q: 2, a: 9 } ] }
   ]
}

Then you can specify multiple conditions on the elements of the answers array with $elemMatch:

db.survey.update(
  { },
  { $pull: { results: { answers: { $elemMatch: { q: 2, a: { $gte: 8 } } } } } },
  { multi: true }
)

1. $set

The $set operator replaces the value of a field with the specified value.

{ $set: { <field1>: <value1>, ... } }

Behavior :

a. If the field does not exist, $set will add a new field with the specified value, provided that the new field does not violate a type constraint.

b.If you specify a dotted path for a non-existent field, $set will create the embedded documents as needed to fulfill the dotted path to the field.

c.If you specify multiple field-value pairs, $set will update or create each field.

I. Set Top-Level Fields
Consider a collection products with the following document:

db.Products.insert({
  sku: "abc123",
  quantity: 250,
  instock: true,
  reorder: false,
  details: { model: "14Q2", make: "xyz" },
  tags: [ "apparel", "clothing" ],
  ratings: [ { by: "ijk", rating: 4 } ]
})
db.Products.update(
   { sku: "abc123" },
   { $set:
      {
        quantity: 500,
        details: { model: "14Q3", make: "abc" },
        tags: [ "coats", "outerwear", "clothing" ],
        ratings: [ { by: "pqr", rating: 5 } ]
      }
   }
)
//OUTPUT : 
/* 1 */
{
    "_id" : ObjectId("5f12925a02c633f9f578dcdd"),
    "sku" : "abc123",
    "quantity" : 500.0,
    "instock" : true,
    "reorder" : false,
    "details" : {
        "model" : "14Q3",
        "make" : "abc"
    },
    "tags" : [ 
        "coats", 
        "outerwear", 
        "clothing"
    ],
    "ratings" : [ 
        {
            "by" : "pqr",
            "rating" : 5.0
        }
    ]
}

II. Set Fields in Embedded Documents :

db.Products.update(
   { "sku" : "abc123" },
   { $set: { "details.make": "arp" } }
)

III. Set Elements in Arrays

db.Products.update(
   { "sku" : "abc123" },
   { $set:
      {
        "tags.1": "rain gear",
        "ratings.0.rating": 2
      }
   }
)

Leave a Reply

Your email address will not be published. Required fields are marked *