Skip to content

Instantly share code, notes, and snippets.

@prsaya
Last active October 25, 2022 11:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save prsaya/85f8d7756512a72083168ea53c7772ec to your computer and use it in GitHub Desktop.
Save prsaya/85f8d7756512a72083168ea53c7772ec to your computer and use it in GitHub Desktop.
Working with Arrays in MongoDB

Working with Arrays in MongoDB

1. Introduction:

This is about creating an array field in a document (of MongoDB database collection) and performing CRUD operations on it - adding, updating, deleting and querying the array elements. This is using an example posts collection with comments array field. The database name is blogs.

These are code snippets for the article Working with MongoDB Arrays.

These query code snippets run from mongo shell. The query output is also shown.

2. Create and Query a Document

use blogs

NEW_POST =
  { 
    name: "Working with Arrays",
    user: "Database Rebel",
    desc: "Maintaining an array of objects in a document",
    content: "some content...",
    created: ISODate(),
    updated: ISODate(),
    tags: [ "mongodb", "arrays" ]
}

db.posts.insertOne(NEW_POST)

db.posts.findOne()

The output:

{
        "_id" : ObjectId("5ec55af811ac5e2e2aafb2b9"),
        "name" : "Working with Arrays",
        "user" : "Database Rebel",
        "desc" : "Maintaining an array of objects in a document",
        "content" : "some content...",
        "created" : ISODate("2020-05-20T16:28:55.468Z"),
        "updated" : ISODate("2020-05-20T16:28:55.468Z"),
        "tags" : [
                "mongodb",
                "arrays"
        ]
}

3. Add an Array Element

NEW_COMMENT = {
  user: "DB Learner",
  text: "Nice post, can I know more about the arrays in MongoDB?",
  updated: ISODate()
}

db.posts.updateOne( 
  { _id : ObjectId("5ec55af811ac5e2e2aafb2b9") },
  { $push: { comments: NEW_COMMENT } }
)

db.posts.findOne()

The output:

{
        "_id" : ObjectId("5ec55af811ac5e2e2aafb2b9"),
        "name" : "Working with Arrays",
         ...
        "comments" : [
                {
                        "user" : "DB Learner",
                        "text" : "Nice post, can I know more about the arrays in MongoDB?",
                        "updated" : ISODate("2020-05-20T16:35:57.461Z")
                },
                {
                        "user" : "Database Rebel",
                        "text" : "Thank you, please look for updates",
                        "updated" : ISODate("2020-05-20T16:48:25.506Z")
                }
        ]
}

4. Update an Array Element

NEW_CONTENT = "Thank you, please look for updates - updated the post"

db.posts.updateOne( 
  { _id : ObjectId("5ec55af811ac5e2e2aafb2b9"), "comments.user": "Database Rebel" },
  { $set: { "comments.$.text": NEW_CONTENT } }
)

The updated comment:

"comments" : [
                {
                        "user" : "Database Rebel",
                        "text" : "Thank you, please look for updates - updated",
                        "updated" : ISODate("2020-05-20T16:48:25.506Z")
                }
 ]

5. Delete an Array Element

db.posts.updateOne( 
  { _id" : ObjectId("5ec55af811ac5e2e2aafb2b9") },
  { $pull: { comments: { user: "Database Rebel" } } }
)

6. Add a New Field to all Objects in the Array

db.posts.updateOne( 
  { "_id : ObjectId("5ec55af811ac5e2e2aafb2b9") },
  { $set: { "comments.$[].likes": 0 } }
)

An updated element:

{
    "user" : "DB Learner",
    "text" : "Nice post, can I know more about the arrays in MongoDB?",
    "updated" : ISODate("2020-05-20T16:35:57.461Z"),
    "likes" : 0
}

7. Update a Specific Array Element Based on a Condition

// add a new element
NEW_COMMENT = {
  user: "DB Learner",
  text: "Thanks for the updates!",
  updated: ISODate()
}

db.posts.updateOne( 
  { _id : ObjectId("5ec55af811ac5e2e2aafb2b9") },
  { $push: { comments: NEW_COMMENT } }
)

db.posts.updateOne( 
  { "_id" : ObjectId("5ec55af811ac5e2e2aafb2b9") },
  { $inc: { "comments.$[ele].likes": 1 } },
  { arrayFilters: [ { "ele.user": "DB Learner",  "ele.likes": { $exists: false } } ] }
)

// end.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment