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.
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/
@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}});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.