0

I need to add a value to mongo db inner object with array element without looking at other value. Can some one advice to do this.

Eg: take order collection as,

{_id:'ssdeiieirei33',userId: 213828, enrolLment:{"ADMIN":{"TERM1":["COURSE1","COURSE3"]},"STUD":{"TERM2":["COURSE1","COURSE2"]}}}

Here I need to add new enrollment(COURSE3) (STUD:{"TERM2":["COURSE3"]}) to enrolLment column with out reading it . this should be the result;

 {_id:'ssdeiieirei33',userId: 213828, enrolLment:{"ADMIN":{"TERM1":["COURSE1","COURSE3"]},"STUD":{"TERM2":["COURSE1","COURSE2","COURSE3"]}}}

Is it possible?

3
  • 1
    possible duplicate of (MongoDB Java) $push into array Commented Sep 28, 2015 at 11:10
  • Yes, you are looking for the $push operator (or alternatively $addToSet when you want to avoid duplicates) Commented Sep 28, 2015 at 11:13
  • I updated the question with my real collection. sorry about inconvenience Commented Sep 28, 2015 at 12:38

1 Answer 1

1

Depending on your needs you can use $addToSet if you don't want duplicates or $push if duplicates are allowed.

From your wording it seems to me that you want to use $addToSet, but please clarify.

UPDATE

You should use

collection.update({condition},
    {
        $addToSet: {enrolLment.$userName.$Term : "COURSE3"}
    },
callback)

Note that I did not test my code. enrolLment.$userName.$Term in your case should be enrolLment.ADMIN.TERM2. But if you have them in the condition then you can use the $ notation to access those variables.

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

2 Comments

As @JohnnyHK said, your question is not really valid. Do you want to have only counts of items? Then use {..., items: {'pen':3, 'book':4}}. That way you don't need any arrays, since you basically have a hash-map.
I updated the question with my real collection. sorry about inconvenience

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.