如何删除MongoDB中的嵌入式文档记录?

时间:2011-12-08 05:56:32

标签: ruby mongodb

我有一名文件患者和一份嵌入式文件程序。不知何故,我在我的程序表中导入了重复的条目,这导致为特定患者创建了重复的过程嵌入文档。 现在我需要删除那些重复的条目,但我无法这样做。 当我在重复的嵌入式文档记录上使用删除方法时,它会抛出错误,说“删除是一个私有方法”。 我做过类似的事情

if type == "procedures"

  count = 0
  user.access_self
  unique_procedures = Set.new
  user.procedures.each{|each_proc|
    each_proc.access_self
    if !unique_procedures.include?("#{each_proc.access_self.name} #{each_proc.hid_code}")
      unique_procedures.add("#{each_proc.access_self.name} #{each_proc.hid_code}")
    else
      each_proc.delete
      count = count + 1
    end
  }
  if count > 0
    puts "#{user.full_name} has #{count} duplicate procedures."
    puts "#{count} duplicate procedures deleted."
  else
    puts "#{user.full_name} has no procedures."
  end
  return count
end

如何删除嵌入文档的重复条目?

1 个答案:

答案 0 :(得分:2)

好的,这是一个例子:

require 'rubygems'
require 'mongo'

# make the connection
@conn = Mongo::Connection.new
@db = @conn['test']
@patients = @db['patients']

# clear out the old collection
@patients.drop

# create some fake procedures
tummy_ache = { :technical_name => 'apendectomy' }
nose_job = { :technical_name => 'rhinoplasty' }

# create some fake patients with duplicate procedures
patient1 = {
    :full_name => 'Tyler Brock',
    :procedures => [ tummy_ache, nose_job, nose_job ]
}

patient2 = {
    :full_name => 'Fake Name',
    :procedures => [ tummy_ache, tummy_ache, nose_job ]
}

patients = [patient1, patient2]

# put the patients into the collection
@patients.insert patients

# remove duplicates
@patients.find.each do |patient|
    patient['procedures'] = patient['procedures'].inject([]) do |list, procedure|
        list << procedure unless list.include?(procedure)
        list
    end
    @patients.update({"_id" => patient["_id"]}, patient)
end

# print collection -- now sans duplicates
@patients.find.each do |patient|
    puts patient.inspect
end