Insert documents into MongoDB only if all fields a

2019-08-03 16:28发布

问题:

I have the following class structure:

public class DBTestItem
{
    public int p0;
    public int p1;
    public int p2;
    public int p3;
    public int p4;
    public int p5;
    public int p6;
    public int p7;
    public string data;
}

public sealed class MongoTestItem : DBTestItem
{
    public ObjectId _id;
}

_id is meaningless to me. p0 - p7 represent a composite key, and data represents the value.

I want to save MongoTestItem documents where data is unique, and ideally without performing updates as they would be meaningless. In other words, save if data's value does not exist in the collection.

I have looked at the documentation, but can't quite find how to write the statement to meet the above.

I did create a different structure where p0 - p7 makes a composite _id and data is a List, in which case the statement is as follows:

var query = Query<MdbData>.EQ(x => x._id, doc._id);
var update = Update<MdbData>.Push(x => x.data, "somenewvalue");
col.Update(query, update, UpdateFlags.Upsert);

This has different semantics, so the upsert is OK.

I want to write the above so I can evaluate the performance difference.

回答1:

If you just want to check if the value of the field 'data' doesn't appear in other documents, you can create a Unique index for data.

Or if you want to check the field data doesn't exist in that document (when updating), you can use the $exist operator with the Query Builder



回答2:

Are you saying that you want to only insert if "data" is unique? If so, could you create a unique constraint on "data", and update with safeMode ?

I'd also be tempted to structure your composite key like this;

db.so.insert(
 {
    _id: {
      p0:1,
      p1:0,
      p2:0,
      p3:0,
      p4:0,
      p5:0,
      p6:0,
      p7:0,
    },
    data:"apiceofdata",
 }
);