本文整理汇总了C#中MongoDB.Driver.FindAndModifyArgs类的典型用法代码示例。如果您正苦于以下问题:C# FindAndModifyArgs类的具体用法?C# FindAndModifyArgs怎么用?C# FindAndModifyArgs使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
FindAndModifyArgs类属于MongoDB.Driver命名空间,在下文中一共展示了FindAndModifyArgs类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: FindAndModifyTest1
public void FindAndModifyTest1()
{
string entryMessage1 = "entry 1";
AddMongoEntry(entryMessage1, MONGO_COLLECTION_1_NAME);
List<Entry> results = new List<Entry>(_readerT.Read(MONGO_COLLECTION_1_NAME, "TimeStamp", _beforeTest, DateTime.Now));
Assert.AreEqual(1, results.Count());
Assert.AreEqual(entryMessage1, results[0].Message);
var searchQuery = Query.EQ("Message", entryMessage1);
var update = Update.Set("Message", MONGO_EDITED_TEXT);
var sortBy = SortBy.Descending("TimeStamp");
FindAndModifyArgs findAndModifyArgs = new FindAndModifyArgs();
findAndModifyArgs.Query = searchQuery;
findAndModifyArgs.SortBy = sortBy;
findAndModifyArgs.Update = update;
findAndModifyArgs.Upsert = true;
findAndModifyArgs.VersionReturned = FindAndModifyDocumentVersion.Modified;
_AsyncDelegateUpdaterT.FindAndModifyAsync(MONGO_COLLECTION_1_NAME, findAndModifyArgs);
_updaterAutoResetEvent.WaitOne();
Assert.IsTrue(_findAndModifyResult.Ok, "FindAndModifyResult from FindAndModify not OK");
Assert.IsNull(_findAndModifyResult.ErrorMessage);
Assert.IsNotNull(_findAndModifyResult.ModifiedDocument);
results = new List<Entry>(_readerT.Read(MONGO_COLLECTION_1_NAME, "TimeStamp", _beforeTest, DateTime.Now));
Assert.AreEqual(1, results.Count());
Assert.AreEqual(MONGO_EDITED_TEXT, results[0].Message);/*This field we modified via FindAndModify...*/
}
示例2: GenerateId
public long GenerateId()
{
bool lockTaken = false;
try
{
// Entering single-thread block
_lock.Enter(ref lockTaken);
// Incrementing id if it belongs to reserved block
if (_isIdBlockReserved && ++_idBlockOffset < IdBlockLength)
{
return _idBlockBegin + _idBlockOffset;
}
// Reserving new id block as atomic operation
MongoCollection<SequenceEntity> sequenceCollection = _sequenceRepository.Collection;
IMongoQuery query = Query.EQ("Name", TrackingUrlSequenceName);
IMongoSortBy sortBy = SortBy.Null;
UpdateBuilder update = Update.Inc("Current", IdBlockLength);
var argument = new FindAndModifyArgs { Query = query, SortBy = sortBy, Update = update, VersionReturned = FindAndModifyDocumentVersion.Modified };
FindAndModifyResult result = sequenceCollection.FindAndModify(argument);
BsonDocument sequence = result.ModifiedDocument;
if (sequence == null)
{
// first block
_idBlockBegin = 0;
_idBlockOffset = 0;
sequenceCollection.Insert(new SequenceEntity { Name = TrackingUrlSequenceName, Current = 0 });
}
else
{
_idBlockBegin = sequence.GetValue("Current").AsInt64;
_idBlockOffset = 0;
}
_isIdBlockReserved = true;
long newId = _idBlockBegin + _idBlockOffset;
return newId;
}
finally
{
if (lockTaken)
{
// Exiting single-thread block
_lock.Exit();
}
}
}
示例3: DoDequeueMessage
/// <summary>
/// Returns the object at the beginning of the message queue,
/// and updates its status to remove it from the queue.
/// </summary>
/// <returns>The object at the beginning of the message queue, or <see langword="null"/>.</returns>
protected override MessageContainer DoDequeueMessage()
{
MongoCollection<BsonDocument> collection = this.database.GetCollection(MessagingDatabase.MessageQueue._COLLECTION_NAME);
FindAndModifyArgs args = new FindAndModifyArgs
{
Query = Query.EQ(MessagingDatabase.MessageQueue.STATUS, MessageStatus.Queued.ToString("G")),
Update = Update.Set(MessagingDatabase.MessageQueue.STATUS, MessageStatus.Outgoing.ToString("G"))
};
FindAndModifyResult result = collection.FindAndModify(args);
if (result.ModifiedDocument == null)
{
return null;
}
return BsonConverter.ConvertToObjectViaJson<MessageContainer>(result.ModifiedDocument);
}
示例4: CreditBlock
public static long CreditBlock(long account, long amount)
{
try
{
MongoCollection accountCollection = DataHelper.Database.GetCollection("finance_account");
FindAndModifyArgs args = new FindAndModifyArgs();
args.Query = Query.And(
Query.EQ("_id", account)
);
args.Update = MongoDB.Driver.Builders.Update.Inc("blocked", -amount);
FindAndModifyResult result = accountCollection.FindAndModify(args);
return result.ModifiedDocument.GetElement("available_balance").Value.ToInt64();
}
catch
{
return -1;
}
}
示例5: FindAndModifyTest5
public void FindAndModifyTest5()
{
_AsyncDelegateUpdaterT.AsyncFindAndModifyCompleted -= new FindAndModifyCompletedEvent(_updaterAsyncT_AsyncFindAndModifyCompleted);
string entryMessage1 = "entry 1";
AddMongoEntry(entryMessage1, MONGO_COLLECTION_1_NAME);
List<Entry> results = new List<Entry>(_readerT.Read(MONGO_COLLECTION_1_NAME, "TimeStamp", _beforeTest, DateTime.Now));
Assert.AreEqual(1, results.Count());
Assert.AreEqual(entryMessage1, results[0].Message);
var searchQuery = Query.EQ("Message", entryMessage1);
var update = Update.Set("Message", MONGO_EDITED_TEXT);
var sortBy = SortBy.Descending("TimeStamp");
IMongoFields fields = Fields.Include("TimeStamp");
FindAndModifyArgs findAndModifyArgs = new FindAndModifyArgs();
findAndModifyArgs.Query = searchQuery;
findAndModifyArgs.SortBy = sortBy;
findAndModifyArgs.Update = update;
findAndModifyArgs.Fields = fields;
findAndModifyArgs.Upsert = true;
findAndModifyArgs.VersionReturned = FindAndModifyDocumentVersion.Modified;
_AsyncDelegateUpdaterT.FindAndModifyAsync(MONGO_COLLECTION_1_NAME, findAndModifyArgs);
Thread.Sleep(2000); // wait 2 seconds to show that event handler will not pick up callback
Assert.IsNull(_findAndModifyResult);
results = new List<Entry>(_readerT.Read(MONGO_COLLECTION_1_NAME, "TimeStamp", _beforeTest, DateTime.Now));
Assert.AreEqual(1, results.Count());
Assert.AreEqual(MONGO_EDITED_TEXT, results[0].Message);/*This field we modified via FindAndModify...*/
}
示例6: NextKey
public string NextKey(string name)
{
var collection = database.GetCollection(Collection.COUNTERS);
FindAndModifyArgs args = new FindAndModifyArgs();
args.Query = MonQ.Query.EQ("_id", name);
args.Update = MonQ.Update.Inc(Field.COUNTERVALUE, 1);
args.Fields = MonQ.Fields.Include(Field.COUNTERVALUE);
args.Upsert = true;
args.VersionReturned = FindAndModifyDocumentVersion.Modified;
FindAndModifyResult result = collection.FindAndModify(args);
BsonDocument document = result.ModifiedDocument;
string value = Field.KEYPREFIX + document[Field.COUNTERVALUE].AsInt32.ToString();
return value;
}
示例7: GetNextSquence
public long GetNextSquence(string SequenceName)
{
try
{
MongoCollection sequenceCollection = Database.GetCollection("counters");
FindAndModifyArgs args = new FindAndModifyArgs();
args.Query = Query.EQ("_id", SequenceName);
args.Update = MongoDB.Driver.Builders.Update.Inc("seq", 1);
FindAndModifyResult result = sequenceCollection.FindAndModify(args);
return result.ModifiedDocument.GetElement("seq").Value.ToInt64();
}
catch
{
dynamic bs = new DynamicObj();
bs._id = SequenceName;
bs.seq = 2;
Insert("counters", bs);
return 1;
}
}
示例8: TestFindAndModifyUpsert
public void TestFindAndModifyUpsert()
{
_collection.RemoveAll();
var args = new FindAndModifyArgs
{
Query = Query.EQ("name", "Tom"),
Update = Update.Inc("count", 1),
Upsert = true,
VersionReturned = FindAndModifyDocumentVersion.Modified
};
var result = _collection.FindAndModify(args);
Assert.AreEqual("Tom", result.ModifiedDocument["name"].AsString);
Assert.AreEqual(1, result.ModifiedDocument["count"].AsInt32);
}
示例9: TestFindAndModifyWithMaxTime
public void TestFindAndModifyWithMaxTime()
{
if (_primary.Supports(FeatureId.MaxTime))
{
using (var failpoint = new FailPoint(FailPointName.MaxTimeAlwaysTimeout, _server, _primary))
{
if (failpoint.IsSupported())
{
failpoint.SetAlwaysOn();
var args = new FindAndModifyArgs
{
Update = Update.Set("x", 1),
MaxTime = TimeSpan.FromMilliseconds(1)
};
Assert.Throws<ExecutionTimeoutException>(() => _collection.FindAndModify(args));
}
}
}
}
示例10: FindAndModifyAs
public object FindAndModifyAs(Type documentType, IMongoQuery query, IMongoSortBy sortBy, IMongoUpdate update, IMongoFields fields, bool returnNew, bool upsert, out UpdateResult result)
{
var args = new FindAndModifyArgs();
args.Query = query;
args.SortBy = sortBy;
args.Update = update;
args.Fields = fields;
args.Upsert = upsert;
args.VersionReturned = returnNew ? FindAndModifyDocumentVersion.Modified : FindAndModifyDocumentVersion.Original;
var r = _this.FindAndModify(args);
result = new FindAndModifyUpdateResult(r);
return r.GetModifiedDocumentAs(documentType);
}
示例11: MakeTransacton
internal static dynamic MakeTransacton(dynamic master_trans, dynamic cfg)
{
try
{
for (int i = 0; i < cfg.transactions.Length; i++)
{
dynamic trans = cfg.transactions[i];
trans._id = master_trans._id + "." + i.ToString().PadLeft(2, '0');
trans.account = String.Format(trans.account, master_trans.accounts);
trans.finance_amount = (trans.amount_type == "F") ? (long)trans.amount : (long)Math.Round((decimal)(trans.amount * master_trans.amount / 100));
MongoCollection accounts = DataHelper._database.GetCollection("finance_account");
FindAndModifyArgs args = new FindAndModifyArgs();
if (trans.type == "debit")
{
args.Query = Query.And(
Query.EQ("_id", trans.account),
Query.GTE("balance", trans.finance_amount));
args.Update = Update.Inc("balance", -trans.finance_amount).Inc("debit", trans.finance_amount);
}
else
{
args.Query =
Query.EQ("_id", trans.account);
args.Update = Update.Inc("balance", trans.finance_amount).Inc("credit", trans.finance_amount);
}
FindAndModifyResult result = accounts.FindAndModify(args);
if (!result.Ok)
{
trans.status = "ERROR";
DataHelper.Save("finance_transaction_detail", trans);
master_trans.status = "ERROR";
return master_trans;
}
else
{
trans.status = "DONE";
DataHelper.Save("finance_transaction_detail", trans);
}
}
master_trans.status = "DONE";
}
catch
{
master_trans.status = "ERROR";
}
return master_trans;
}
示例12: FindAndModifyResult
private FindAndModifyResult FindAndModifyResult(string ObjName)
{
var args = new FindAndModifyArgs()
{
Query = Query.EQ("document", ObjName),
SortBy = null,
Update = Update.Inc("last", (long)1),
VersionReturned = FindAndModifyDocumentVersion.Modified,
Upsert = true
};
FindAndModifyResult result =MongoMapperHelper.Db("Counters", true).GetCollection("Counters").FindAndModify(args);
return result;
}
示例13: Get
/// <summary>
/// Get a non running message from queue
/// </summary>
/// <param name="query">query where top level fields do not contain operators. Lower level fields can however. eg: valid {a: {$gt: 1}, "b.c": 3}, invalid {$and: [{...}, {...}]}</param>
/// <param name="resetRunning">duration before this message is considered abandoned and will be given with another call to Get()</param>
/// <param name="wait">duration to keep polling before returning null</param>
/// <param name="poll">duration between poll attempts</param>
/// <param name="approximateWait">whether to fluctuate the wait time randomly by +-10 percent. This ensures Get() calls seperate in time when multiple Queues are used in loops started at the same time</param>
/// <returns>message or null</returns>
/// <exception cref="ArgumentNullException">query is null</exception>
public Message Get(QueryDocument query, TimeSpan resetRunning, TimeSpan wait, TimeSpan poll, bool approximateWait)
{
if (query == null)
throw new ArgumentNullException ("query");
//reset stuck messages
collection.Update(
new QueryDocument { { "running", true }, { "resetTimestamp", new BsonDocument("$lte", DateTime.UtcNow) } },
new UpdateDocument("$set", new BsonDocument("running", false)),
UpdateFlags.Multi
);
var builtQuery = new QueryDocument("running", false);
foreach (var field in query)
builtQuery.Add("payload." + field.Name, field.Value);
builtQuery.Add("earliestGet", new BsonDocument("$lte", DateTime.UtcNow));
var resetTimestamp = DateTime.UtcNow;
try
{
resetTimestamp += resetRunning;
}
catch (ArgumentOutOfRangeException)
{
resetTimestamp = resetRunning > TimeSpan.Zero ? DateTime.MaxValue : DateTime.MinValue;
}
var sort = new SortByDocument { { "priority", 1 }, { "created", 1 } };
var update = new UpdateDocument("$set", new BsonDocument { { "running", true }, { "resetTimestamp", resetTimestamp } });
var fields = new FieldsDocument { { "payload", 1 }, { "streams", 1 } };
var end = DateTime.UtcNow;
try
{
if (approximateWait)
//fluctuate randomly by 10 percent
wait += TimeSpan.FromMilliseconds(wait.TotalMilliseconds * GetRandomDouble(-0.1, 0.1));
end += wait;
}
catch (Exception e)
{
if (!(e is OverflowException) && !(e is ArgumentOutOfRangeException))
throw e;//cant cover
end = wait > TimeSpan.Zero ? DateTime.MaxValue : DateTime.MinValue;
}
while (true)
{
var findModifyArgs = new FindAndModifyArgs { Query = builtQuery, SortBy = sort, Update = update, Fields = fields, Upsert = false };
var message = collection.FindAndModify(findModifyArgs).ModifiedDocument;
if (message != null)
{
var handleStreams = new List<KeyValuePair<BsonValue, Stream>>();
var messageStreams = new Dictionary<string, Stream>();
foreach (var streamId in message["streams"].AsBsonArray)
{
var fileInfo = gridfs.FindOneById(streamId);
var stream = fileInfo.OpenRead();
handleStreams.Add(new KeyValuePair<BsonValue, Stream>(streamId, stream));
messageStreams.Add(fileInfo.Name, stream);
}
var handle = new Handle(message["_id"].AsObjectId, handleStreams);
return new Message(handle, message["payload"].AsBsonDocument, messageStreams);
}
if (DateTime.UtcNow >= end)
return null;
try
{
Thread.Sleep(poll);
}
catch (ArgumentOutOfRangeException)
{
if (poll < TimeSpan.Zero)
poll = TimeSpan.Zero;
else
poll = TimeSpan.FromMilliseconds(int.MaxValue);
Thread.Sleep(poll);
}
if (DateTime.UtcNow >= end)
//.........这里部分代码省略.........
示例14: FindAndModifyTest2
public async void FindAndModifyTest2()
{
string entryMessage1 = "entry 1";
AddMongoEntry(entryMessage1, MONGO_COLLECTION_1_NAME);
List<Entry> results = new List<Entry>(_readerT.Read(MONGO_COLLECTION_1_NAME, "TimeStamp", _beforeTest, DateTime.Now));
Assert.AreEqual(1, results.Count());
Assert.AreEqual(entryMessage1, results[0].Message);
var searchQuery = Query.EQ("Message", entryMessage1);
var update = Update.Set("Message", MONGO_EDITED_TEXT);
var sortBy = SortBy.Descending("TimeStamp");
FindAndModifyArgs findAndModifyArgs = new FindAndModifyArgs();
findAndModifyArgs.Query = searchQuery;
findAndModifyArgs.SortBy = sortBy;
findAndModifyArgs.Update = update;
findAndModifyArgs.Upsert = false;
FindAndModifyResult findAndModifyResult = await _asyncUpdaterT.FindAndModifyAsync(MONGO_COLLECTION_1_NAME, findAndModifyArgs);
Assert.IsTrue(findAndModifyResult.Ok);
Assert.IsNull(findAndModifyResult.ErrorMessage);
Assert.IsNotNull(findAndModifyResult.ModifiedDocument);
findAndModifyArgs = new FindAndModifyArgs();
findAndModifyArgs.Query = searchQuery;
findAndModifyArgs.SortBy = sortBy;
findAndModifyArgs.Update = update;
findAndModifyArgs.Upsert = false;
findAndModifyResult = await _asyncUpdaterT.FindAndModifyAsync(MONGO_COLLECTION_1_NAME, findAndModifyArgs);
Assert.IsTrue(findAndModifyResult.Ok);
Assert.IsNull(findAndModifyResult.ErrorMessage);
Assert.IsNull(findAndModifyResult.ModifiedDocument);
results = new List<Entry>(_readerT.Read(MONGO_COLLECTION_1_NAME, "TimeStamp", _beforeTest, DateTime.Now));
Assert.AreEqual(1, results.Count());
Assert.AreEqual(MONGO_EDITED_TEXT, results[0].Message);/*This field we modified via FindAndModify...*/
}
示例15: TestFindAndModifyReplaceWithWriteConcernError
public void TestFindAndModifyReplaceWithWriteConcernError()
{
RequireServer.Where(clusterTypes: ClusterTypes.ReplicaSet);
_collection.RemoveAll();
_collection.Insert(new BsonDocument { { "_id", 1 }, { "x", 1 } });
var collectionSettings = new MongoCollectionSettings
{
WriteConcern = new WriteConcern(9)
};
var collection = _database.GetCollection(_collection.Name, collectionSettings);
var args = new FindAndModifyArgs
{
Query = Query.EQ("_id", 1),
Update = Update.Replace(new BsonDocument { { "_id", 1 }, { "x", 2 } }),
VersionReturned = FindAndModifyDocumentVersion.Modified
};
BsonDocument modifiedDocument;
if (_server.BuildInfo.Version >= new Version(3, 2, 0))
{
Action action = () => collection.FindAndModify(args);
var exception = action.ShouldThrow<MongoWriteConcernException>().Which;
var commandResult = exception.Result;
modifiedDocument = commandResult["value"].AsBsonDocument;
}
else
{
var result = collection.FindAndModify(args);
modifiedDocument = result.ModifiedDocument;
}
modifiedDocument.Should().Be("{ _id : 1, x : 2 }");
}