Corbfon
Corbfon

Reputation: 3634

MongoDB how to reference object's properties in query

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")
}

Upvotes: 0

Views: 161

Answers (1)

Rahul Kumar
Rahul Kumar

Reputation: 2831

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)});

Upvotes: 1

Related Questions