skip to Main Content

I want to retrieve the specific data using an array-values, but I don’t know how to deal with it.

URL is like http://localhost/api/data?sym=aa&bb&cc

DB documents are like:

{"symbol":"aa","price":1.1}
{"symbol":"bb","price":1.2}
{"symbol":"cc","price":1.3}
{"symbol":"dd","price":1.4}
{"symbol":"ee","price":1.5}

the expected result is:

[   
{"symbol":"aa","price":1.1}
{"symbol":"bb","price":1.2}
{"symbol":"cc","price":1.3}
]

My code is:

    [HttpGet()]
    public IEnumerable<Data> Get(string sym)
    {
        symbol = sym.Split('&');

        //connect to database and collections
        var client = new MongoClient("mongodb+srv://.....");
        var db = client.GetDatabase("...");
        var _portf = db.GetCollection<Data>("...");
        return _portf.Find(???).ToList();
    }

??? is where I have failed to find a solution. or I am completely wrong with the find() method.
I really need your help. Thank you!

2

Answers


  1. Chosen as BEST ANSWER

    I've found a very promising way which works perfectly. Thanks to this video

    rewrite the code"

    [HttpGet()]
        public IEnumerable<Data> Get(string sym)
        {
            var symlist = sym.Split('&');
    
            //connect to database and collections
            var client = new MongoClient("mongodb+srv://.....");
            var db = client.GetDatabase("...");
            var _portf = db.GetCollection<Data>("...");
    
         -->var fitlerDefinition = Builders<Findata>.Filter.In(a => a.Symbol, symlist);
    
            return _portf.Find(fitlerDefinition).ToList();
        }
    

  2. Find takes in a FilterDefinition object. For example, a common way of getting a document from MongoDB by its ID would be:

    public T LoadRecordById<T>(string table, Guid id)
    {
        var collection = db.GetCollection<T>(table);
        var filter = Builders<T>.Filter.Eq("Id", id);
    
        return collection.Find(filter).First();
    }
    

    You can combine multiple FilterDefinition objects together using the Or method:

        var filter1 = Builders<T>.Filter.Eq("symbol", symbol);
        var filter2 = Builders<T>.Filter.Eq("symbol", symbol);
        var filter3 = Builders<T>.Filter.Eq("symbol", symbol);
    
        var filter = Builders<T>.Filter.Or(filter1, filter2, filter3);
    

    Hope this helps (it does not hurt to be nice, does it, @Dharman?)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search