Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add key-value pair to object in MongoDB

If I have a document with the following basic structure:

{
  ...
  Monday: { a:1, b:2 },
  Tuesday: { c:3, d:4 }
  ...
}

Am I able to 'push' an additional key:value pair to Monday's value? Result would be:

{
  Monday: { a:1, b:2, z:8 },
  Tuesday: { c:3, d:4 }
  ...
}

The $push operator seems to only work for arrays.

like image 331
flimflam57 Avatar asked Aug 11 '16 04:08

flimflam57


People also ask

How do you store key-value pairs?

A key-value database is a type of nonrelational database that uses a simple key-value method to store data. A key-value database stores data as a collection of key-value pairs in which a key serves as a unique identifier. Both keys and values can be anything, ranging from simple objects to complex compound objects.

How do you write a key to a value pair?

A key-value pair consists of two related data elements: A key, which is a constant that defines the data set (e.g., gender, color, price), and a value, which is a variable that belongs to the set (e.g., male/female, green, 100). Fully formed, a key-value pair could look like these: gender = male. color = green.

What is key-value pair in MongoDB?

Learn more about MongoDB Atlas. Key value databases, also known as key value stores, are database types where data is stored in a “key-value” format and optimized for reading and writing that data. The data is fetched by a unique key or a number of unique keys to retrieve the associated value with each key.

Which object can store data in key-value form?

The dictionary stores objects as key-value pairs and can be used to represent complex real-world data.


1 Answers

Just do something like that

db.foo.update({"_id" :ObjectId("...") },{$set : {"Monday.z":8}})
like image 122
DAXaholic Avatar answered Sep 25 '22 02:09

DAXaholic