I am new to MongoDB and I would like to ask how to make a new field for the element, which represents for the size of another field in that element. For example: - I have the element such like:
{
"_id" : ObjectId("57e1ffcb94d9ae534869c6cd"),
"url" : "http://www.nytimes.com",
"verticals" : [ 1, 2, 3, 4, 5, 12 ]
}
I want to add new field say "numadx" which is the size of "verticals" array, in this case, it's 6. And the result can be:
{
"_id" : ObjectId("57e1ffcb94d9ae534869c6cd"),
"url" : "http://www.nytimes.com",
"verticals" : [ 1, 2, 3, 4, 5, 12 ]
"numadx" : 6
}
I use the command in the terminal:
db.test.update({},{$set:{numadx:{$size: "$verticals"}}},{multi:true})
but it return the error:
"errmsg" : "The dollar ($) prefixed field '$size' in 'numadx.$size' is not valid for storage."
Can someone help me :D ? I do this for sorting the elements in this collection based on numadx field, which helps me know the least to the most number of verticals values of these elements in collection.
Thank you very much.
$addFields
is a new feature in Mongo 3.4 that adresses the question:
it lets you update the record of the collection by storing the product of the aggregation inside the record
db.collection.aggregate(
[ {
"$addFields": { "numadx": { $size: "$verticals" } }
},
{ "$out":"collection"}
]
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With