Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding support for :upsert for single writes, as well as document_id option #72

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions lib/logstash/outputs/mongodb.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ class LogStash::Outputs::Mongodb < LogStash::Outputs::Base
# "_id" field in the event.
config :generateId, :validate => :boolean, :default => false

config :upsert, :validate => :boolean, :default => false, :required => false
config :document_id, :validate => :string, :default => nil, :required => false

# Bulk insert flag, set to true to allow bulk insertion, else it will insert events one by one.
config :bulk, :validate => :boolean, :default => false
Expand Down Expand Up @@ -90,7 +92,9 @@ def receive(event)
end
end

if @generateId
if @document_id != nil
document["_id"] = event.sprintf(@document_id)
elsif @generateId
document["_id"] = BSON::ObjectId.new
end

Expand All @@ -108,7 +112,12 @@ def receive(event)
end
end
else
@db[event.sprintf(@collection)].insert_one(document)
if @upsert
update_result = @db[event.sprintf(@collection)].update_one({_id: document['_id']}, {'$set' => document.reject {|k, v| k == '_id'}},
{:upsert => true})
else
@db[event.sprintf(@collection)].insert_one(document)
end
end
rescue => e
if e.message =~ /^E11000/
Expand Down