简体   繁体   中英

c#: Filter MongoDb collection

I have the following issue: I'm trying to learn how to use MongoDb with c#. I am able to insert items in the collection, but I am not able to filter the existing collection to retrieve one or more items that are meeting the query conditions. Here is my class structure:

    public class TransactionRequest
    {
        public Header Header { get; set; }

        public Transaction Transaction { get; set; }
    }

    public class Header
    {
        public string BusinessId { get; set; }
    }

    public class Transaction
    {
        public string Id { get; set; }
        public string Status { get; set; }
    }

And here is how I'm saving the objects:

        public async Task<TransactionResponse> SaveAsync(TransactionRequest request)
        {
            var document = new BsonDocument
            {
                {"Request", BsonValue.Create(JsonConvert.SerializeObject(request))}
            };

            await this._mongoClient.GetDatabase("MyDatabase").GetCollection<BsonDocument>("Transactions").InsertOneAsync(document, null, CancellationToken.None);

            return new TransactionResponse
            {
                InternalId = document["_id"].ToString(),
                TransactionId = request.Transaction.Id
            };
        }

And the object is saved correctly, as you can see in the image bellow:

插入记录

But how to retrieve the document that contains the object transaction with id 1234?

I am using .net core 2 and MongoDb c# driver version 2.5.

Edit: The collection is a BsonDocument collection, it's not a collection of the type Transactionrequest, so how to map the field id to that bson document? Edit 2: Here is how I've tried to retrieve a document:

public async Task<string> RetrieveResponse(string id)
{

    var cursor =await  this.mongoClient.GetDatabase("MyDatabase")
        .GetCollection<TransactionRequest>("Transactions")
        .FindAsync(t => t.Transaction.Id.Equals("1234"));

    while (await cursor.MoveNextAsync())
    {
        IEnumerable<TransactionRequest> documents = cursor.Current;
        Console.WriteLine(documents.Count()); //this is empty
    }

    return string.Empty;
}

But inside the while loop, the collection retrieved is empty

Your current way of saving creates a ´"Request"´ field on the top level of your document which is not reflected in your entity structure. In order to fix that you should simply not to do the JSON conversion yourself but let the driver do them for you instead:

public async Task<TransactionResponse> SaveAsync(TransactionRequest request)
{
    await this._mongoClient.GetDatabase("MyDatabase")
              .GetCollection<TransactionRequest>("Transactions")
              .InsertOneAsync(request, null, CancellationToken.None);

    // load document - not needed, just for illustration purposes
    this._mongoClient.GetDatabase("MyDatabase")
        .GetCollection<TransactionRequest>("Transactions")
        .Find(t => t.Transaction.Id == request.Transaction.Id);

    return new TransactionResponse
    {
        InternalId = request.Id,
        TransactionId = request.Transaction.Id
    };
}

Then your retrieval should work, too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM