There are two collections:

Trains = new Mongo.Collection('trains'); Passengers = new Mongo.Collection('passengers'); 

One contains data about trains, the other - data about passengers. In each document of the train there is a field numberOfPassengers . Each passenger has a train field. I need the numberOfPassengers each train to store the current number of passengers, with a specific train field. In other words:

 Trains.find({name: 'redTrain'}).numberOfPassengers = Passengers.find({train: 'redTrain').count(); 

How is it possible to link these two collections in this way? So that the document of one collection can dynamically store the number of elements from another collection.

  • one
    Since version 3.2, the monga aggregation framework supports the similarity of joins. Those. data will not be stored (duplicated) in another collection, but you will receive it at the time of the request. - Vladimir Gamalyan

1 answer 1

MongoDB is not intended to bind collections like tables in SQL databases.

In your case, it is best to keep a complete list of passenger objects in the trains collection.

 { "_id" : "0018ff5cb7b1fab5d0980c0bebfb26ec", "train_number" : "324234", "title" : "Number One", "passengers" : [ { "name" : "Robert Willson", "passport" : "238476384" } ] } 

If you want to spread the data on the collections, you can store in the trains _id passengers collection.

 { "_id" : "0018ff5cb7b1fab5d0980c0bebfb26ec", "train_number" : "324234", "title" : "Number One", "passengers" : ["0018ff5cb7b1fab5d09234i798324", "0018ff5cb7b1f21387637841324ff" ] } 
  • Thanks for the fast reply. Also implemented it first, but the problem is as follows. The reactive protocol by which the client and the server are connected can update the fields of a Mongo document only at 1 nesting level. In other words, if you keep a list of passengers in each train, then when the data of one passenger changes, the entire object passengers will be transmitted. Hence the question. - Oner Ksor
  • Storage in the _id passenger collection seems to be a working decision. The passenger must have a train_id field. It will remain only in the methods of adding / deleting passengers to update the field passengers at the train with the passenger train_id, I understand correctly? - Oner Ksor
  • Yes that's right. Check passenger _id in the list of passengers and make an update. - Sequent