0

i have collection called 'test' in that there is a document like:

{
"_id" : 1
"letters" : [ 
        [ "A", "B" ], 
        [ "C", "D" ], 
        [ "A", "E", "B", "F" ]
    ]
}

if i updated the document by using $addToSet like this:

db.getCollection('test').update({"_id" : 1}, {$addToSet:{"letters": ["A", "B"] }})

it will not inserted another value. still the document look like

{
"_id" : 1
"letters" : [ 
        [ "A", "B" ], 
        [ "C", "D" ], 
        [ "A", "E", "B", "F" ]
    ]
}

if im updating like this:

db.getCollection('test').update({"_id" : 1}, {$addToSet:{"letters": ["B", "A"] }})

Now it will update the document like:

{
"_id" : 1
"letters" : [ 
        [ "A", "B" ], 
        [ "C", "D" ], 
        [ "A", "E", "B", "F" ],
        [ "B", "A" ]
    ]
}

my requirment is if im give like this also (["B", "A"]), it will not update that document. Because the same letters are already present in the array.

could anyone can please give the solution.

Nani
  • 446
  • 7
  • 24
  • 1
    try to sort your letters before using addToSet – Shubham Nov 22 '17 at 10:23
  • thx for replying @Shubham. sorting array elements is good idea but database will became slow while using sort(). So can you please tell the solution without sort() – Nani Nov 22 '17 at 10:33
  • I am not suggesting using sort on db level just sort your array before updating on app level – Shubham Nov 22 '17 at 10:35
  • is there any alternative ...? @Shubham – Nani Nov 22 '17 at 10:38
  • you can use update({_id:"somethin",letters:{$nin:[['A','B'],['B','A']]}},{$push{letters:['A','B']}}) here [['A','B'],['B','A']] is all possible combinations of ur letters but now this is extremely slow – Shubham Nov 22 '17 at 10:41
  • There is a good answer regarding a similar question. Read the part about [data modeling considerations](https://stackoverflow.com/questions/18655650/how-sort-an-array-in-a-collection) in specific . Data modeling is quite important when you recognize that you need such things and taking mongodb capabilities in consideration. – Alex P. Nov 22 '17 at 10:58

2 Answers2

0

Try this answer , it works.

Use $push to insert any item in the array in your case.

db.getCollection('stack').update(
       { _id: 1 },
       { $push: { "letters": ["B", "A"] } }
    )

For reference about $push you can view this link -

https://docs.mongodb.com/manual/reference/operator/update/push/

0

@Shubham has the right answer. You should always sort your letters before saving into the document. So your original document should have been (I changed the third array):

{
  "_id" : 1,
  "letters" : [ 
        [ "A", "B" ], 
        [ "C", "D" ], 
        [ "A", "B", "C", "F" ]
    ]
}

Then in your application do the sort. I'm including a Mongo Shell example here.

var input = ["B", "A"];
input.sort();
db.getCollection('test').update({"_id" : 1}, {$addToSet:{"letters":  input}});
Nic Cottrell
  • 9,401
  • 7
  • 53
  • 76