Insert documents into MongoDB only if all fields are unique

佐手、 提交于 2019-12-14 02:37:15

问题


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",
 }
);


来源:https://stackoverflow.com/questions/13046121/insert-documents-into-mongodb-only-if-all-fields-are-unique

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!