我有这个型号:
{
id: long,
items: [{
itemId: long,
amount: decimal
}]
}
编辑: 我需要根据id和itemId增加金额值。
我的查询:
var query = Builders<model>.Filter.And(
Builders<model>.Filter.Eq(_ => _.id, xxx),
Builders<model>.Filter.ElemMatch(_ => _.items, _ => _.itemId == yyy)
);
var update = Builders<modelItem>.Update.Inc(_ => _.amount, incrementalAmount);
但我不知道如何执行查询/更新。
this.Collection.FindOneAndUpdate(query, update);
当然我无法使用此UpdateDefinition,因为我必须使用builder&lt;'model&gt;而不是builder&lt;'modelItem&gt;,而是如何增加子属性?
答案 0 :(得分:0)
只需执行更新
var query = Builders<model>.Filter.And(
Builders<model>.Filter.Eq(_ => _.id, xxx),
Builders<model>.Filter.ElemMatch(_ => _.items, _ => _.itemId == yyy)
);
var update = Builders<model>.Update.Inc(_ => _.amount, incrementalAmount);
然后执行更新:
this.Collection.Update(query, update);
答案 1 :(得分:0)
我终于找到了如何增加子文档:
查询保持不变,我使用operator $更新相应的数组项:
var caf = new BsonDocumentArrayFilterDefinition<ModelItem>(new MongoDB.Bson.BsonDocument("caf.ItemId", new MongoDB.Bson.BsonDocument("$eq", YYYY)));
var oaf = new BsonDocumentArrayFilterDefinition<ModelItem>(new MongoDB.Bson.BsonDocument("oaf.ItemId", new MongoDB.Bson.BsonDocument("$ne", YYYY)));
var query = Builders<Model>.Filter.Eq(_ => _.Id, XXXX);
var update = Builders<Model>.Update.Combine(
Builders<Model>.Update.Inc("Items.$[caf].Amount", incrementValue),
Builders<Model>.Update.Inc("Items.$[oaf].Amount", -incrementValue)
);
await this.Collection.UpdateManyAsync(query, update, new UpdateOptions()
{
ArrayFilters = new List<ArrayFilterDefinition>() { caf, oaf}
});
对于更复杂的增量,我使用arrayfilter:
import {Http} from "@angular/http";
const CONTACT_URL = "./pages/contacts.json"
export class ContactService