I'm trying to set up and update some capped collections in MongoDB using Node.js (using the native MongoDB driver).
My goal is to, upon running app.js, insert documents into a capped collection, and also to update existing documents in a capped collection. Both of these are running on setInterval()
, so every few seconds.
My questions:
- I want to create a collection if the collection does not already exist, but if it does I want to insert a document into it instead. What is the correct way to check this?
- With capped collections, should I even be explicitly creating them first before inserting anything into them? Normally I believe you can just insert things into a collection without explicitly creating them first, but in this case I need to ensure they are capped. Once the capped collection exists I know how to insert new documents into it, the problem is I need some way to handle the app being used for the first time (on a new server) where the collection doesn't already exist, and I want to do this creation using node and not having to jump into the mongo cli.
- The trick here is that the collection needs to be capped, so I can do something like:
db.createCollection("collectionName", { capped : true, size : 100000, max : 5000 } )
. That will create the capped collection for me, but every time I call it it will callcreateCollection()
instead of updating or inserting - if I callcreateCollection()
, once the collection already exists, will it completely overwrite the existing collection? - An alternative is to turn a collection into a capped one with:
db.runCommand({"convertToCapped": "collectionName", size: 100000, max : 5000 });
. The problem with this is that node doesn't seerunCommand()
as a valid function and it errors. Is there something else that I'm meant to be calling to get this to work? It works in the mongo cli but not within node - What type of query do you use to find the first document in a collection? Again, within the mongo cli I can use
db.collections.find()
with some query, but within node it states thatfind()
is not a valid function - How would I use
collection.update()
to add some new fields to an existing document? Lets say the document is some simple object like{key1: "value", key2: "value"}
but I have an object that contains{key3: "value"}
. Key 3 does not exist in the current document, how would I add that to what currently exists? This is somewhat related to #4 above in that I'm not sure what to pass in as the query parameter given thatfind()
doesn't seem to play well with node.