Jose Molina
Jose Molina

Reputation: 55

How to use FIND() for a MongoDB query on a MVC .net C# project

I'm connecting a MongoDB (Azure) with a MVC .NET C# project. The connection and object definition are working very good so far. My problem is when I try to add the method FIND() to return all the data in the object USER.

My Model:

using System;
using System.Collections.Generic;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;
using MongoDB.Driver.Builders;

namespace backendnet.Models
{
    public class MongoCore
    {    
        public class DB
        {
            static MongoClient Client = new MongoClient("mongodb://mydbconnect");
            static public IMongoDatabase Database = Client.GetDatabase("mydb");
            static public IMongoCollection<User> Users = Database.GetCollection<User>("users");
        }

        public class User
        {
            [BsonId]
            public ObjectId Id { get; set; }
            [BsonElement("email")]
            public string Email { get; set; }
            [BsonElement("password")]
            public string Password { get; set; }
            [BsonElement("name")]
            public List<DimensionName> Name { get; set; }
            [BsonElement("address")]
            public List<DimensionAddress> Address { get; set; }
            [BsonElement("permissions")]
            public List<DimensionPermissions> Permissions { get; set; }
            [BsonElement("status")]
            public string Status { get; set; }
            [BsonElement("created")]
            public string Created { get; set; }
            [BsonElement("updated")]
            public string Updated { get; set; }    
        }

        public class DimensionName
        {
            [BsonElement("first")]
            public string First { get; set; }
            [BsonElement("last")]
            public string Last { get; set; }    
        }

        public class DimensionAddress
        {
            [BsonElement("stree")]
            public string Stree { get; set; }
            [BsonElement("number")]
            public string Number { get; set; }
            [BsonElement("city")]
            public string City { get; set; }
            [BsonElement("state")]
            public string State { get; set; }
            [BsonElement("zipcode")]
            public string Zipcode { get; set; }
            [BsonElement("type")]
            public string Type { get; set; }
        }

        public class DimensionPermissions
        {
            [BsonElement("list")]
            public string List { get; set; }
            [BsonElement("create")]
            public string Create { get; set; }
            [BsonElement("edit")]
            public string Edit { get; set; }
            [BsonElement("delete")]
            public string Delete { get; set; }
        }
    }
}

My Controller:

using System;
using System.Collections.Generic;
using System.Web.Mvc;
using backendnet.Models;
using MongoDB.Bson;

namespace backendnet.Controllers
{    
    public class DashboardController : Controller
    {    
        private string _viewFolder = "../Admin/Dashboard";

        public ActionResult Index()
        {
            var results = new MongoCore.DB();
            ViewData["ListPost"] = results.ToJson();

            return View (_viewFolder);
        }            
    }
}

My View partial:

<p>HERE: @ViewData["ListPost"]</p>

I get this:

HERE: { }

So I tried adding in the Model -> DB the method Find:

MongoCursor<User> cursor = Users.Find("Email" != "");

But always show an error:

Expression is always 'true' ["Email" != ""]

May anyone show me what I'm missing here?

Upvotes: 0

Views: 1702

Answers (2)

Ashan Nanayakkara
Ashan Nanayakkara

Reputation: 11

public ActionResult GetUsers()
{
 MongoServer objServer = MongoServer.Create("Server=localhost:27017");
 MongoDatabase objDatabse = objServer.GetDatabase("DBName");
 List UserDetails = objDatabse.GetCollection("Colletion_Name").FindAll().ToList();
 return View(UserDetails);
}

Upvotes: 0

Scornwell
Scornwell

Reputation: 605

I Don't See you calling MongoDB.Find()? I have pasted below my code I use for MongoDB C# driver in order to attain a record based on a key:value pair in my MongoDB database.

The Find or FindAsync method both require a BsonDocument Argument, which can be created using the Builders as seen below. Your filter can be empty, which would get all records since you are not filtering out anything.

Once you call the find method, you will be able to access the information using Lambda, or other query methods. You can see in my query i just need one record so i ask for FirstOrDefault. Hope this helps.

    async Task<Document> IDal.GetRecordAsync(string key, string value)
    {
        try
        {
            if (Database == null) ((IDal)this).StartConnection();
            var filter = Builders<BsonDocument>.Filter.Eq(key, value);
            var cursor = await Collection.FindAsync(filter);
            var bsondocument = cursor.FirstOrDefault();
            return bsondocument == null ? null : _converter.ConvertBsonDocumentToDocument(bsondocument);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
            return null;
        }
    }

Upvotes: 1

Related Questions