SqlSugar/Src/Asp.NetCore2/MongoDb.Ado.data/ExecuteNonQueryItems/InsertManyHandler.cs

32 lines
1016 B
C#
Raw Normal View History

2025-05-02 07:54:16 +08:00
using MongoDB.Bson.Serialization;
using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Text;
2025-05-04 18:39:11 +08:00
using System.Linq;
2025-05-02 07:54:16 +08:00
namespace MongoDb.Ado.data
{
public class InsertManyHandler : IMongoOperationHandler
{
2025-05-04 18:39:11 +08:00
public HandlerContext context { get; set; }
2025-05-02 16:55:48 +08:00
public string operation { get; set; }
2025-05-02 07:54:16 +08:00
public int Handle(IMongoCollection<BsonDocument> collection, string json)
{
var documents = ParseJsonArray(json);
2025-05-04 18:39:11 +08:00
collection.InsertMany(documents);
var objectIds = documents.Select(it=>it["_id"].AsObjectId.ToString()).ToArray();
context.ids = objectIds;
2025-05-02 07:54:16 +08:00
return documents.Count;
}
private List<BsonDocument> ParseJsonArray(string json)
{
if (json.TrimStart().StartsWith("["))
return BsonSerializer.Deserialize<List<BsonDocument>>(json);
return new List<BsonDocument> { BsonDocument.Parse(json) };
}
}
}