仅当所有字段都是唯一的时,才将文档插入MongoDB [英] Insert documents into MongoDB only if all fields are unique

查看:216
本文介绍了仅当所有字段都是唯一的时,才将文档插入MongoDB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下类结构:

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对我来说是无意义的。

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

我想保存 MongoTestItem 文档中的数据是唯一的,并且理想地不执行更新,因为它们将是无意义的。换句话说,如果数据的值在集合中不存在,则保存。

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.

我创建了一个不同的结构,其中p0 - p7使复合_id和数据是一个List,在这种情况下语句如下:

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);

这有不同的语义,因此upsert可以。

This has different semantics, so the upsert is OK.

我想写上面的代码,以便我可以评估性能差异。

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

推荐答案

如果字段data的值未显示在其他文档中,则可以为数据创建唯一索引。

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.

或者如果您想要检查该文档中不存在的字段 data (更新时),您可以使用 $ exists 运算符与查询生成器

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

这篇关于仅当所有字段都是唯一的时,才将文档插入MongoDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆