当我在MongoDB中创建一个新的BsonDocument
时,我有了结构var doct = new BsonDocument
{
{ "fbId", "" },
{ "Name", NameTxt.Text.ToString() },
{ "pass", PasswTxt.Text.ToString() },
{ "Watchtbl", new BsonArray
{
new BsonDocument
{
{ "wid", "" },
{ "name", "" },
{ "Symboles", new BsonArray
{
new BsonDocument
{
{ "Name", "" }
}
}
}
}
}
}
};
我想知道如何删除一些空记录,这是我尝试在MongoDB中获取数据时的样子
{ "_id" : ObjectId("582c77454d08e326104879cb"),
"fbId" : "",
"Name" : "user",
"pass" : "user",
"Watchtbl" :
[
{ "wid" : "", "name" : "", "Symboles" : [ { "Name" : "" } ] },
{ "wid" : "0000", "name" : "bought stock2", "Symboles" : [ ] },
{ "wid" : "", "name" : "", "Symboles" : [ { "Name" : "" } ] },
{ "wid" : "", "name" : "", "Symboles" : [ { "Name" : "" } ] },
{ "wid" : "", "name" : "", "Symboles" : [ { "Name" : "" } ] },
{ "wid" : "", "name" : "", "Symboles" : [ { "Name" : "" } ] }
] }
答案 0 :(得分:0)
序列化数据后,您可以对POCO类进行任何复杂的更新。请查看以下内容:
// add user into datagridview from MongoDB Colelction Watchtbl
var client = new MongoClient("mongodb://dataservername:27017");
var database = client.GetDatabase("WatchTblDB");
var collectionWatchtbl = database.GetCollection<BsonDocument>("UserWatchtbl");
var filter = new BsonDocument();
var users = new List<UserWatchTblCls>();
var cursor = collectionWatchtbl.FindAsync(filter).Result;
cursor.ForEachAsync(batch =>
{
users.Add(BsonSerializer.Deserialize<UserWatchTblCls>(batch));
});
foreach (var user in users)
{
List<WatchTblCls> removables = new List<WatchTblCls>();
foreach (var watchTbl in user.WatchTbls)
if (string.IsNullOrEmpty(watchTbl.WID) && string.IsNullOrEmpty(watchTbl.Name) && watchTbl.Symbols.Count == 1 && string.IsNullOrEmpty(watchTbl.Symbols.Single().Name))
removables.Add(watchTbl);
foreach (WatchTblCls removable in removables)
user.WatchTbls.Remove(removable);
collectionWatchtbl.UpdateOne(Builders<BsonDocument>.Filter.Eq("_id", user.Id), Builders<BsonDocument>.Update.Set("Watchtbl", user.WatchTbls));
}
这些类看起来像这样:
public class UserWatchTblCls
{
[BsonId]
[BsonElement("_id")]
public ObjectId Id { get; set; }
public string fbId { get; set; }
public string Name { get; set; }
[BsonElement("pass")]
public string Pass { get; set; }
[BsonElement("Watchtbl")]
public List<WatchTblCls> WatchTbls { get; set; }
}
public class WatchTblCls
{
[BsonElement("wid")]
public string WID { get; set; }
[BsonElement("name")]
public string Name { get; set; }
[BsonElement("Symboles")]
public List<SymboleCls> Symbols { get; set; }
}
public class SymboleCls
{
public string Name { get; set; }
}
答案 1 :(得分:0)
另一种可能的解决方案是一次性使用pull:
collectionWatchtbl.UpdateMany(
Builders<BsonDocument>.Filter.Empty,
Builders<BsonDocument>.Update.PullFilter("Watchtbl",
Builders<BsonDocument>.Filter.Eq("name", "") &
Builders<BsonDocument>.Filter.Eq("wid", "") &
Builders<BsonDocument>.Filter.Size("Symboles", 1) &
Builders<BsonDocument>.Filter.ElemMatch("Symboles",
Builders<BsonDocument>.Filter.Eq("Name", ""))));