0

I am attempting to run a script on my MongoDB which will set teacher_ids[] = [document.owner_id]. owner_id already exists on all of the objects in the collection. My current attempt looks like this:

db.getCollection('readings').update({ $where: "this.teacher_ids[0] != this.owner_id" }, { $set: { "teacher_ids": [this.owner_id] }}, { multi: true })

Everything almost works, except that the document looks like

doc: {
    owner_id: "some_id",
    teacher_ids: [undefined]
}

which must mean that this in the second argument of update is not referencing the document. How do I get it to set:

teacher_ids = [document.owner_id]

Example Document

{
    "_id" : ObjectId("586f07bd6a2169fdffb0563b"),
    "teacher_ids" : [],
    "owner_id" : "57c268dd6c9fd2320035e67e",
    "source" : "http://www.omfgdogs.com",
    "title" : "Test",
    "updatedAt" : ISODate("2017-01-28T07:43:46.597Z"),
    "createdAt" : ISODate("2017-01-06T02:58:05.699Z")
}

1 Answer 1

1

I don't think in update component you can reference any other field value by this or otherwise.

It can be done through script though

db.getCollection('readings').find({ $where: "this.teacher_ids[0] != this.owner_id" }).forEach(function(x){x.teacher_ids = [x.owner_id]; db.readings.save(x)});
Sign up to request clarification or add additional context in comments.

7 Comments

I ran this query on a sandbox collection and it set all of the arrays to [undefined], any ideas?
can you add a sample document from the collection? looks like owner_id is missing in those document.
Just added an example document for you!
Ok actually, it appears that the script works fine, it just updates about 10 documents at a time before quitting. Do you have any ideas about making it stay alive until all documents from the query are updated?
I tried this script with the sample document, worked fine. needed to change the name of the collection in save call in foreach function.
|

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.