0

I have a collection in MongoDB called Results

I have a field in the collection called Positions

"Positions": {
    "X": "1",
    "Y": "2"
}

I want to update this field to be an array of positions

 "Positions": [{
        "X": "1",
        "Y": "2"}, {X:"100", Y:"200"}]

I want to do this using the command line, is it possible? I have tried the following

use MyMongoDb 

followed by

db.getCollection("Results").find( { "Positions" : { $type : 2 } } ).snapshot().forEach( function (x) {x.Positions = [ Positions ];db.jobs.save(x);});

I get an exception

QUERY    [js] uncaught exception: TypeError: db.getCollection(...).find(...).snapshot is not a function :
@(shell):1:1

1 Answer 1

2

snapshot is not a function of cursor says error stack... And it is right.

Anyway I propose you to use the following code

db.getCollection("Results")
   .find( { "Positions" : { $type : 2 } } )
   .forEach( function(x) {
      x.Positions = [ x.Positions ];
      db.getCollection("Results").save(x);
   });

Please note that I have replaced x.Positions = [ Positions ] with x.Positions = [ x.Positions ] as Positions variable is not declared. And also db.jobs.save(x) with db.getCollection("Results").save(x) as I understood you wanted to update same collection.

I also would recommend to migrate depreciated save method to update or replaceOne.

Sign up to request clarification or add additional context in comments.

7 Comments

thanks for your feedback, the error is gone and the code execute but it just proceeds to a new line with the ">" character and the data did not change?
1. Check if "Results" collection has documents for specified selector. For instance: db.getCollection("Results").find( { "Positions" : { $type : 2 } } ).count() should return anything greater than 0
2. If you really don't have _id field on document replace forEach function with: function(x) { db.getCollection("Results").remove(x); x.Positions = [ x.Positions ]; db.getCollection("Results").insert(x);}
the query returns 0? why is that?
There is a a _id field defined in the collection "_id": { "$oid": "5e95b70fb54af5cb6ce49793" },
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.