Is there a method for inserting a new document which does not contain certain properties in MongoDB?
For example, say I want to insert a document which looks like:
{
'f_name': 'Jim',
'l_name': 'Jones',
'age': 21,
'country': 'UK',
...etc...
}
But I wanted to insert this document only if a document containing
{
'f_name': 'Jim',
'l_name': 'Jones'
}
did not already exist. Is there a way of doing this in a single operation (e.g. like an upsert, but without modifying any existing matching documents if one exists), or does this have to be done in two seperate operations (a lookup to see if one exists, then an insert)?
It’s not majorly important, but it would be quite useful to know about and could save a lot of time!
You can use one of two options:
An upsert like so:
db.col.update({f_name: ‘Jim’, l_name: ‘Jones’}, {//your doc here}, {upsert: true})
This will basically search for a document where these fields already have these values and updates (you can just update the fields with their same value) or inserts if the find criteria does not return results.
A last ditch try it is to use two queries, however the upsert above should work quite nicely.