Pooh
Pooh

Reputation: 15

Mongoid insert embedded document to many documents

Let's say, I have two models

class User
  embeds_many :notifications
  field :age, type :Integer

class Notification
  embedded_in :user
  field :message, type: String

I want to create notification and add it to all users, matching specific criteria. All I came up with is:

notification = Notification.new
notification.message = "Hello"
User.where(:age.ge => 18).push(:notifications, notification)

But this won't work. Any idea?

UPD: I know, there's a way to make it work like so:

users = User.where(:age.ge => 18)
users.each do |user|
  notification = Notification.new
  notification.message = "Hello"
  user.notifications << notification
  user.save
end

But this seems ugly and inefficient code.

UPD2: Finally, this code works, directly working with driver, as Winfield stated:

users = User.where(:age.ge => 18)
notification = Notification.new
notification.message = "Hello"
User.collection.update(users.selector, {'$push' => {notifications: notification.as_document}}, multi: true)

Upvotes: 1

Views: 1087

Answers (1)

Winfield
Winfield

Reputation: 19145

You can probably do this at the raw Mongo Driver level:

db.users.update({}, { $push: { notifications: { message: 'Hello!' } } })

However, if your goal is to accomplish a mass-messaging feature, you might be better off making a special collection for these Notifications and having your application code pull system-wide notifications and user-targeted notifications.

Having to update every single user object in your system to send a mass message is not a scalable design.

Upvotes: 1

Related Questions