Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add new field which is the size of another field of the document [duplicate]

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.

like image 237
Blurie Avatar asked Nov 27 '22 14:11

Blurie


1 Answers

$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"}
     ]    
)
like image 79
c24b Avatar answered Nov 29 '22 05:11

c24b