Can view be updated when it's base collection updated?

Hello,

I want to create a view which will contains data from two collections. This view C is created by aggregation which is executed from collection A and look up to collect B. In this way the view C will have data from A and B. Is there a way to update the view C when A or B updated?
Thanks for the support,

James

This is how standard views work.

Hello Steeve,

Thank you for the answer.

Just confirm if my understanding is correct. You mean if I create a view from collection A and B, it will keep updated when the data in A or B is changed. So in this case I just need to read the data from the view, even if the collection A or B changed, I don’t need to re-create the view, just read it and I can get new data, right?

Thanks,

James

It is clear from the documentation that you

you simply

and you

It is actually trivial to test.

/* mongosh> */ db.A.insertOne( { _id : 0 , user : 1 })
{ acknowledged: true, insertedId: 0 }
/* mongosh> */ db.B.insertOne( { _id : 1 , name : "Steeve" })
{ acknowledged: true, insertedId: 1 }
/* mongosh> */ db.createView( "C" , "A" , [ { "$lookup" : { "from" : "B" , localField : "user" , as : "_result" , foreignField : "_id"}}])
{ ok: 1 }
/* mongosh> */ db.C.find()
{ _id: 0, user: 1, _result: [ { _id: 1, name: 'Steeve' } ] }
/* mongosh> */ db.B.updateOne( { _id : 1 } , { $set : { "first_name" : "Steeve" , "last_name" : "Juneau"}})
{ acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0 }
/* mongosh> */ db.C.find()
{ _id: 0,
  user: 1,
  _result: 
   [ { _id: 1,
       name: 'Steeve',
       first_name: 'Steeve',
       last_name: 'Juneau' } ] }

@steevej , Hello Steeve, got it. Thanks a lot for the help!

1 Like