0

I have database with documents, each document has the following structure:

{ 
 name: "name1",
 group: "group1",
 source: "source1",
 context: "context1"
}

I want to add new document only if there is no other documents with the same name and group (group and name is the key). how can I create single query with this condition, that first checks the condition and then add the new document to the collection ?

Ashh
  • 44,693
  • 14
  • 105
  • 132
Ohad
  • 1,563
  • 2
  • 20
  • 44

1 Answers1

1

You could try a different approach: create a unique index on both "name" and "group".

Unique indexes in the official documentation: https://docs.mongodb.com/manual/core/index-unique/

Run this in the command shell:

db.your_collection.createIndex( { "name": 1, "group": 1 }, { unique: true } ) { "createdCollectionAutomatically" : false, "numIndexesBefore" : 1, "numIndexesAfter" : 2, "ok" : 1 }

When you'll try to insert another document with the same data you'll receive an error and the data won't be inserted:

> db.your_collection.insert({ name: "name1",group: "group1",source: "source1",context: "context1"})
WriteResult({
    "nInserted" : 0,
    "writeError" : {
        "code" : 11000,
        "errmsg" : "E11000 duplicate key error collection: test.some index: name_1_group_1 dup key: { : \"name1\", : \"group1\" }"
    }
})

For MongoDb > 2.4 tere is findAndModify: https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/

Dan Ionescu
  • 3,135
  • 1
  • 12
  • 17
  • how will it help? please explain – Ohad Oct 30 '19 at 08:44
  • but if I will insert data with the same data of the indexes fields but with different data in the fields which are not part of the index? – Ohad Oct 30 '19 at 08:57
  • 1
    It will fail of course. Take a look at findAndModify if you're using MongoDb > 2.4: https://docs.mongodb.com/manual/reference/method/db.collection.findAndModify/ – Dan Ionescu Oct 30 '19 at 08:59