插入C#MongoDB中的嵌套数组 [英] Insert into nested array in C# MongoDB
问题描述
在MongoDB中名为Users
的集合中有以下document
.我试图将<SpecificBeer>
插入mycellar
cellar
的beersInCellar[]
中.我已经尝试了filter
和update
对象中的各种组合,但是无法将头放在插入嵌套数组中.我知道如何find
一个document
并将东西插入其中,而不是不插入该文档的数组中.
I have the following document
in a collection called Users
in MongoDB. I am trying to insert a <SpecificBeer>
into beersInCellar[]
of the mycellar
cellar
. I've tried all kinds of combinations in the filter
and update
objects but just can't wrap my head around inserting into a nested array. I know how to find
a document
and insert things into it, just not into an array in that document.
{
"_id" : ObjectId("5920751b6d4f6a27cf7985a8"),
"name" : "FullName",
"emailAddress" : "emailaddress@example.com",
"cellars" : [
{
"cellarId" : "mycellar",
"cellarName" : "My Cellar",
"beersInCellar" : [ ]
}
]
}
SpecificBeer模型:
SpecificBeer model:
public class SpecificBeer
{
public string ourid
{
get
{
return ID.ToString();
}
set
{
ID = ObjectId.Parse(value);
}
}
[BsonId]
private ObjectId ID {get; set;}
public string year { get; set; }
public string variant { get; set; }
public string quantity { get; set; }
public string numberForTrade { get; set; }
}
插入方法
public async Task<SpecificBeer> AddBeerToList(string id, SpecificBeer specificBeer, string cellarId)
{
var filter = Builders<User>.Filter.Eq(e => e.userId, id) & Builders<User>.Filter.Eq(e => e.cellars, cellarId);
var update = Builders<Cellar>.Update.Push<SpecificBeer>(e => e.beersInCellar, specificBeer);
await _collection.FindOneAndUpdateAsync(filter, update);
return specificBeer;
}
推荐答案
您必须使用您必须包括cellars
中的字段(cellarId
),以便mongoDB定位元素的索引,并将占位符($
)替换为更新部分中从查询部分找到的索引,以进行推送beersInCellar
中的元素.
You've to include the field(cellarId
) from the cellars
for mongoDB to locate the index of element and replace the placeholder($
) with the found index from query part in the update part to push the element in beersInCellar
.
类似
var filter = Builders<User>.Filter.Eq(e => e.name, "FullName") & Builders<User>.Filter.ElemMatch(e => e.cellars, Builders<Cellar>.Filter.Eq(e => e.cellarId, "mycellar"));
var update = Builders<User>.Update.Push(e => e.cellars[-1].beersInCellar, specificBeer);
Shell查询以供参考:
Shell Query for reference:
db.collection.update({"name" : "FullName", "cellars":{$elemMatch:{"cellarId":"mycellar"}}},{$push:{"cellars.$.beersInCellar":{"quantity":1, "year":1986}}})
MongoDB不具有对数组内部嵌套数组中的字段(例如quantity
)进行更新的一流支持.
MongoDB doesn't have first class support for updating fields ( for example quantity
) in the nesting arrays inside arrays.
您可以跟踪将允许进行多级更新的吉拉.
You can track the jira which is going to allow multiple level updates.
https://jira.mongodb.org/browse/SERVER-27089
您现在可能想要重新访问您的结构.尝试将beersInCellar
数组提升为顶级.
You may want to revisit your structure for now. Try promoting the beersInCellar
arrays to top level.
这篇关于插入C#MongoDB中的嵌套数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!