|
1 | 1 | # MongoDB Coding Practice
|
2 | 2 |
|
3 |
| -## Q. ***Mention the command to insert a document in a database called school and collection called persons?*** |
| 3 | +## Q. ***Mention the command to insert a document in a database called company and collection called employee?*** |
| 4 | + |
| 5 | +```js |
| 6 | +use company; |
| 7 | +db.employee.insert( { name: "John", email: "john.k@gmail.com" } ) |
| 8 | +``` |
| 9 | + |
| 10 | +<div align="right"> |
| 11 | + <b><a href="#">↥ back to top</a></b> |
| 12 | +</div> |
| 13 | + |
4 | 14 | ## Q. ***Mention the command to check whether you are on the master server or not?***
|
5 |
| -## Q. ***How can I combine data from multiple collections into one collection?*** |
| 15 | + |
| 16 | +```js |
| 17 | +db.isMaster() |
| 18 | +``` |
| 19 | + |
| 20 | +<div align="right"> |
| 21 | + <b><a href="#">↥ back to top</a></b> |
| 22 | +</div> |
| 23 | + |
| 24 | +## Q. ***How to combine data from multiple collections into one collection?*** |
| 25 | + |
| 26 | +**$lookup** |
| 27 | + |
| 28 | +Performs a left outer join to an unsharded collection in the same database to filter in documents from the “joined” collection for processing. To each input document, the `$lookup` stage adds a new array field whose elements are the matching documents from the “joined” collection. The `$lookup` stage passes these reshaped documents to the next stage. |
| 29 | + |
| 30 | +**Syntax** |
| 31 | + |
| 32 | +```js |
| 33 | +{ |
| 34 | + $lookup: |
| 35 | + { |
| 36 | + from: <collection to join>, |
| 37 | + localField: <field from the input documents>, |
| 38 | + foreignField: <field from the documents of the "from" collection>, |
| 39 | + as: <output array field> |
| 40 | + } |
| 41 | +} |
| 42 | +``` |
| 43 | + |
| 44 | +<div align="right"> |
| 45 | + <b><a href="#">↥ back to top</a></b> |
| 46 | +</div> |
| 47 | + |
6 | 48 | ## Q. ***How do I perform the SQL JOIN equivalent in MongoDB?***
|
7 |
| -## Q. ***How to query MongoDB with %like%?*** |
| 49 | + |
| 50 | +```js |
| 51 | +// Sample Records |
| 52 | + |
| 53 | +comments |
| 54 | + { uid:12345, pid:444, comment="blah" } |
| 55 | + { uid:12345, pid:888, comment="asdf" } |
| 56 | + { uid:99999, pid:444, comment="qwer" } |
| 57 | + |
| 58 | +users |
| 59 | + { uid:12345, name:"john" } |
| 60 | + { uid:99999, name:"mia" } |
| 61 | +``` |
| 62 | + |
| 63 | +**Answers** |
| 64 | + |
| 65 | +```js |
| 66 | +{ |
| 67 | + $lookup: |
| 68 | + { |
| 69 | + from: <collection to join>, |
| 70 | + localField: <field from the input documents>, |
| 71 | + foreignField: <field from the documents of the "from" collection>, |
| 72 | + as: <output array field> |
| 73 | + } |
| 74 | +} |
| 75 | +``` |
| 76 | + |
| 77 | +## Q. ***How to query MongoDB with "like"?*** |
| 78 | + |
| 79 | +```js |
| 80 | +db.users.insert({name: 'paulo'}) |
| 81 | +db.users.insert({name: 'patric'}) |
| 82 | +db.users.insert({name: 'pedro'}) |
| 83 | + |
| 84 | +db.users.find({name: /a/}) //like '%a%' |
| 85 | +db.users.find({name: /^pa/}) //like 'pa%' |
| 86 | +db.users.find({name: /ro$/}) //like '%ro' |
| 87 | +``` |
| 88 | + |
| 89 | +<div align="right"> |
| 90 | + <b><a href="#">↥ back to top</a></b> |
| 91 | +</div> |
| 92 | + |
8 | 93 | ## Q. ***Find objects between two dates MongoDB?***
|
9 |
| -## Q. ***How to query MongoDB with “like”?*** |
10 |
| -## Q. ***Update MongoDB field using value of another field*** |
| 94 | + |
| 95 | +Operator `$gte` and `$lt` is used to find objects between two dates in MongoDB. |
| 96 | + |
| 97 | +**Example**: Creating a collection |
| 98 | + |
| 99 | +```js |
| 100 | +>db.order.insert({"OrderId":1,"OrderAddrees":"US","OrderDateTime":ISODate("2020-02-19")}; |
| 101 | +WriteResult({ "nInserted" : 1 }) |
| 102 | + |
| 103 | +>db.order.insert({"OrderId":2,"OrderAddrees":"UK","OrderDateTime":ISODate("2020-02-26")}; |
| 104 | +WriteResult({ "nInserted" : 1 }) |
| 105 | +``` |
| 106 | +
|
| 107 | +Display all documents from the collection using `find()` method. |
| 108 | +
|
| 109 | +```js |
| 110 | +> db.order.find().pretty(); |
| 111 | + |
| 112 | +// Output |
| 113 | +{ |
| 114 | + "_id" : ObjectId("5c6c072068174aae23f5ef57"), |
| 115 | + "OrderId" : 1, |
| 116 | + "OrderAddrees" : "US", |
| 117 | + "OrderDateTime" : ISODate("2020-02-19T00:00:00Z") |
| 118 | +} |
| 119 | +{ |
| 120 | + "_id" : ObjectId("5c6c073568174aae23f5ef58"), |
| 121 | + "OrderId" : 2, |
| 122 | + "OrderAddrees" : "UK", |
| 123 | + "OrderDateTime" : ISODate("2020-02-26T00:00:00Z") |
| 124 | +} |
| 125 | +``` |
| 126 | +
|
| 127 | +Here is the query to find objects between two dates: |
| 128 | +
|
| 129 | +```js |
| 130 | +> db.order.find({"OrderDateTime":{ $gte:ISODate("2020-02-10"), $lt:ISODate("2020-02-21") } |
| 131 | +}).pretty(); |
| 132 | + |
| 133 | + |
| 134 | +// Output |
| 135 | +{ |
| 136 | + "_id" : ObjectId("5c6c072068174aae23f5ef57"), |
| 137 | + "OrderId" : 1, |
| 138 | + "OrderAddrees" : "US", |
| 139 | + "OrderDateTime" : ISODate("2020-02-19T00:00:00Z") |
| 140 | +} |
| 141 | +``` |
| 142 | +
|
| 143 | +<div align="right"> |
| 144 | + <b><a href="#">↥ back to top</a></b> |
| 145 | +</div> |
| 146 | +
|
| 147 | +## Q. ***Is it possible to update MongoDB field using value of another field?*** |
| 148 | +
|
| 149 | +The aggregate function can be used to update MongoDB field using the value of another field. |
| 150 | +
|
| 151 | +**Example** |
| 152 | +
|
| 153 | +```js |
| 154 | +db.collection.<update method>( |
| 155 | + {}, |
| 156 | + [ |
| 157 | + {"$set": {"name": { "$concat": ["$firstName", " ", "$lastName"]}}} |
| 158 | + ] |
| 159 | +) |
| 160 | +``` |
| 161 | +
|
| 162 | +<div align="right"> |
| 163 | + <b><a href="#">↥ back to top</a></b> |
| 164 | +</div> |
| 165 | +
|
11 | 166 | ## Q. ***How to check if a field contains a substring?***
|
| 167 | +
|
| 168 | +The `$regex` operator can be used to check if a field contains a string in MongoDB. |
| 169 | +
|
| 170 | +```js |
| 171 | +db.users.findOne({"username" : {$regex : ".*some_string.*"}}); |
| 172 | +``` |
| 173 | +
|
| 174 | +<div align="right"> |
| 175 | + <b><a href="#">↥ back to top</a></b> |
| 176 | +</div> |
| 177 | +
|
12 | 178 | ## Q. ***How to get the last N records from find?***
|
13 |
| -## Q. ***MongoDB relationships. What to use - embed or reference?*** |
| 179 | +
|
| 180 | +```js |
| 181 | +// Syntax |
| 182 | +db.<CollectionName>.find().sort({$natural:-1}).limit(value) |
| 183 | + |
| 184 | + |
| 185 | +// Example |
| 186 | +db.employee.find().sort({$natural:-1}).limit(100) |
| 187 | +``` |
| 188 | +
|
| 189 | +<div align="right"> |
| 190 | + <b><a href="#">↥ back to top</a></b> |
| 191 | +</div> |
| 192 | +
|
14 | 193 | ## Q. ***How to remove a field completely from a MongoDB document?***
|
15 |
| -## Q. ***By default, MongoDB writes and reads data from both primary and secondary replica sets. True or False.*** |
| 194 | +
|
| 195 | +How do I remove words completely from all the documents in this collection? |
| 196 | +
|
| 197 | +```js |
| 198 | +{ |
| 199 | + name: 'book', |
| 200 | + tags: { |
| 201 | + words: ['abc','123'], // <-- remove it comletely |
| 202 | + lat: 33, |
| 203 | + long: 22 |
| 204 | + } |
| 205 | +} |
| 206 | +``` |
| 207 | +
|
| 208 | +**Answer** |
| 209 | +
|
| 210 | +```js |
| 211 | +db.example.update({}, {$unset: {words: 1}}, false, true); |
| 212 | +``` |
| 213 | +
|
| 214 | +<div align="right"> |
| 215 | + <b><a href="#">↥ back to top</a></b> |
| 216 | +</div> |
| 217 | +
|
16 | 218 | ## Q. ***How to find MongoDB records where array field is not empty?***
|
17 |
| -## Q. ***Is it possible to update MongoDB field using value of another field?*** |
| 219 | +
|
| 220 | +```js |
| 221 | +db.inventory.find({ pictures: { $exists: true, $ne: [] } }) |
| 222 | +``` |
| 223 | +
|
| 224 | +<div align="right"> |
| 225 | + <b><a href="#">↥ back to top</a></b> |
| 226 | +</div> |
| 227 | +
|
18 | 228 | ## Q. ***How to find document with array that contains a specific value?***
|
19 | 229 |
|
| 230 | +Populate the inventory collection |
| 231 | +
|
| 232 | +```js |
| 233 | +db.inventory.insertMany([ |
| 234 | + { item: "journal", qty: 25, tags: ["blank", "red"], dim_cm: [ 14, 21 ] }, |
| 235 | + { item: "notebook", qty: 50, tags: ["red", "blank"], dim_cm: [ 14, 21 ] }, |
| 236 | + { item: "paper", qty: 100, tags: ["red", "blank", "plain"], dim_cm: [ 14, 21 ] }, |
| 237 | + { item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] }, |
| 238 | + { item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] } |
| 239 | +]); |
| 240 | +``` |
| 241 | +
|
| 242 | +To query if the array field contains at least one element with the specified value, use the filter { `<field>`: `<value>` } where `<value>` is the element value. |
| 243 | +
|
| 244 | +```js |
| 245 | +db.inventory.find( { tags: "red" } ) |
| 246 | +``` |
| 247 | +
|
20 | 248 | <div align="right">
|
21 | 249 | <b><a href="#">↥ back to top</a></b>
|
22 | 250 | </div>
|
0 commit comments