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?

Dinusha
  • 696
  • 1
  • 14
  • 27
  • 1
    possible duplicate of [(MongoDB Java) $push into array](http://stackoverflow.com/questions/15436542/mongodb-java-push-into-array) – Vishwas Sep 28 '15 at 11:10
  • Yes, you are looking for the [`$push`](http://docs.mongodb.org/manual/reference/operator/update/push/) operator (or alternatively [`$addToSet`](http://docs.mongodb.org/manual/reference/operator/update/addToSet/) when you want to avoid duplicates) – Philipp Sep 28 '15 at 11:13
  • I updated the question with my real collection. sorry about inconvenience – Dinusha Sep 28 '15 at 12:38

1 Answers1

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.

Pio
  • 4,044
  • 11
  • 46
  • 81
  • 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. – Pio Sep 28 '15 at 12:18
  • I updated the question with my real collection. sorry about inconvenience – Dinusha Sep 28 '15 at 12:38