1

I want to add a new field to a an object after i search the specific object, Database looks like this:

{
    "_id": {
        "$oid": "608378ef1ae6b1368c6220c6"
    },
    "username": "paul",
    "password": "cacavaca123",
    "question": "q1",
    "answer": "cutu"
}
{
    "_id": {
        "$oid": "6084c1b557f2242bcc629440"
    },
    "username": "mircea",
    "password": "123456",
    "question": "q1",
    "answer": "cutu"
}

And i want to search in db for the object with username: paul and add a new field friends:[alex], I have tried this but its not working:

MongoClient.connect(uri, function(err, db) {
        var dbc = db.db("chat");
        dbc.collection("accounts").find({username: { $eq: user}}).aggregate( [
            {
              $addFields: {
                frequent:[new_friend]
              }
            }
        ])

        db.close();
    });

Also if you know, can you tell me how to update that array of friends and add a new friend to that array?

1 Answer 1

2

You've to use update query to do so

Read - updateOne

Demo - https://mongoplayground.net/p/mrTg0DKtnrW

db.collection.update(
{ "username": "paul" },
{
  $set: {
    friends: ["alex" ]
  }
})

Aggregation demo - https://mongoplayground.net/p/yiJgkrgdeHZ

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.