claymonstr
claymonstr

Reputation: 11

mongodb $addToSet failure, specify full document to insert

I've done a bit of research on this and haven't come across anything that jumps out at me immediately as what I'm looking for.

Say we have a document (or documents) in a collection that look something like this:

//First example document
{
  "_id": "JK",
  "letters": ["J", "K"]
}
//Second example document
{
  "_id": "LM",
  "letters": ["L"]
}

So I run a query like the one below to see if I have any matching documents and of course I don't so I expect to get null.

> db.example.findOne({"_id": "LM", "letters": {"$in": ["M"]}})
null

So I do an update and add "M" to the letters array on the documents (syntax may not be quite right):

> db.example.update({"_id": "LM"}, {"$addToSet": {"letters": "M"}})

I run the possibility of not having a matching _id, so the findOne would would also return null given the example documents in the collection for this query.

> db.example.findOne({"_id": "AB", "letters": {"$in": ["A"]}})
null

Based on the way I've constructed the above query, I get null back when "A" is not found in letters or the _id of "AB" is not found on any document. In this case I know that this document isn't in there because I know what is in the collection.

What I'd like to do is keep my update query from above with $addToSet and modify it to use upsert WHILE ALSO specifying the document to insert in the event that $addToSet fails due to the document not existing to cut down on database transactions. Is this possible? Or will I have to break up my queries a bit in order to accommodate this?

Because this information may influence answers: I do my querying through mongo shell and pymongo.

mongo version: 2.6.11

pymongo version: 2.8

Thanks for any help!

EDIT: So after a break and a bit more digging, it seems setOnInsert does what I was looking for. I do believe that this probably solves my issue, but I've not had a chance to test yet.

Upvotes: 1

Views: 763

Answers (0)

Related Questions