Page tree

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Info

CAST supports MongoDB via its NoSQL for .NET extension. As Amazon DocumentDB is MongoDB compatible, the support also applies to Amazon DocumentDB. Details about how this support is provided for .NET source code is discussed below.

Supported Client Libraries

MongoDB Mongodb.Net Driver dotnet driver 2.x

Supported Operations

Operation

Methods Supported

Create
Insert
CreateCollection


Expand
  • CreateCollectionAsync
  • GetCollectionInsert
    titleInsert methods Suppported
    • MongoDB.Driver.IMongoCollection.InsertOne
    • MongoDB.Driver.IMongoCollection.InsertOneAsync
    • MongoDB.Driver.IMongoCollection.InsertManyAsync
  • InsertMany
    • MongoDB.Driver.IMongoCollection.InsertMany


    Update


    Expand
    titleUpdate Methods Supported

    MongoDB.Driver.IMongoCollection.UpdateManyAsync

    MongoDB.Driver.IMongoCollection.UpdateOneAsync

    MongoDB.Driver.IMongoCollection.UpdateOne

    MongoDB.Driver.IMongoCollection.UpdateMany

    MongoDB.Driver.IMongoCollection.ReplaceOne

    MongoDB.Driver.IMongoCollection.ReplaceOneAsync

    UpdateBulkWriteAsync

    MongoDB.Driver.IMongoCollectionExtensions.ReplaceOne

    MongoDB.Driver.IMongoCollectionExtensions.ReplaceOneAsync

    MongoDB.Driver.IMongoCollectionExtensions.UpdateMany

    MongoDB.Driver.IMongoCollectionExtensions.UpdateManyAsync

    MongoDB.Driver.IMongoCollectionExtensions.UpdateOne

    MongoDB.Driver.IMongoCollectionExtensions.UpdateOneAsync


    Select


    Expand
    titleSelect Methods Supported

    MongoDB.Driver.IMongoCollection.Find

    MongoDB.Driver.IMongoCollection.FindSync

    FindAsync

    FindOne

    FindOneAs

    Exists

    FindOneAndDelete

    FindOneAndDeleteAync

    FindOneAndReplace

    FindOneAndReplaceAsync

    FindOneAndUpdate

    FinOneAndUpdateAsync

    FindAllAs

    FindAll

    FindOneByIdAs

    BulkWrite

    MongoDB.Driver.IMongoCollection.FindAsync

    MongoDB.Driver.IMongoCollection.FindOneAndDelete

    MongoDB.Driver.IMongoCollection.FindOneAndDeleteAync

    MongoDB.Driver.IMongoCollection.FindOneAndReplace

    MongoDB.Driver.IMongoCollection.FindOneAndReplaceAsync

    MongoDB.Driver.IMongoCollection.FindOneAndUpdate

    MongoDB.Driver.IMongoCollection.FindOneAndUpdateAsync

    MongoDB.Driver.IMongoCollection.Count

    MongoDB.Driver.IMongoCollection.CountAsync

    MongoDB.Driver.IMongoCollection.Aggregate

    MongoDB.Driver.IMongoCollection.AggregateAsync

    MongoDB.Driver.IMongoCollection.BulkWrite

    MongoDB.Driver.IMongoCollection.BulkWriteAsync

    MongoDB.Driver.IMongoCollectionExtensions.ReplaceOne

    MongoDB.Driver.IMongoCollectionExtensions.ReplaceOneAsync

    MongoDB.Driver.IMongoCollectionExtensions.UpdateMany

    MongoDB.Driver.IMongoCollectionExtensions.UpdateManyAsync

    MongoDB.Driver.IMongoCollectionExtensions.UpdateOne

    MongoDB.Driver.IMongoCollectionExtensions.UpdateOneAsync

    MongoDB.Driver.IMongoCollectionExtensions.FindOneAndDelete

    MongoDB.Driver.IMongoCollectionExtensions.FindOneAndDeleteAsync

    MongoDB.Driver.IMongoCollectionExtensions.FindOneAndReplace

    MongoDB.Driver.IMongoCollectionExtensions.FindOneAndReplaceAsync

    MongoDB.Driver.IMongoCollectionExtensions.FindOneAndUpdate

    MongoDB.Driver.IMongoCollectionExtensions.FindOneAndUpdateAsync

    MongoDB.Driver.IMongoCollectionExtensions.Distinct

    MongoDB.Driver.IMongoCollectionExtensions.DistinctAsync

    MongoDB.Driver.IMongoCollectionExtensions.CountDocuments

    MongoDB.Driver.IMongoCollectionExtensions.CountDocumentsAsync

    MongoDB.Driver.IMongoCollectionExtensions.Find

    MongoDB.Driver.IMongoCollectionExtensions.Aggregate

    MongoDB.Driver.IMongoCollectionExtensions.Count

    MongoDB.Driver.IMongoCollectionExtensions.CountAsync


    Delete 


    Expand
    titleDelete Methods Supported

    MongoDB.Driver.IMongoCollection.DeleteMany

    MongoDB.Driver.IMongoCollection.DeleteManyAsync

    MongoDB.Driver.IMongoCollection.DeleteOne

    MongoDB.Driver.IMongoCollection.DeleteOneAsync

    MongoDB.Driver.IMongoCollection.FindOneAndDelete

    MongoDB.Driver.IMongoCollection.FindOneAndDeleteAsync

    Remove

    MongoDB.Driver.IMongoCollectionExtensions.DeleteOne

    MongoDB.Driver.IMongoCollectionExtensions.DeleteOneAsync

    MongoDB.Driver.IMongoCollectionExtensions.DeleteMany

    MongoDB.Driver.IMongoCollectionExtensions.DeleteManyAsync


    Objects

    DotNet MongoDB connection
    IconDescription

    Image Removed

    DotNet MongoDB database

    DotNet MongoDB collection

    Image Removed

    DotNet unknown MongoDB connection

    DotNet unknown MongoDB database

    DotNet unknown MongoDB collection

    ...

    Links are created for transaction and function point needs:

    Link typeSource and destination of link Methods supported
    parentLink 
    belongsTo
    Between

    From DotNet MongoDB

    Connection

    Collection object

    and

    to DotNet MongoDB Database object

    Between MongoDB Database object and MongoDB


     useInsertLink

    Between the caller .NET Method (C#) object and DotNet  MongoDB Collection object

    •  GetDatabase
    useLink


    Between the caller .NET

    Class / Method objects and MongoDB Collection objects
    • CreateCollection
    • CreateCollectionAsync
    • GetCollection
     useInsertLink

    Method (C#) object and DotNet unknown MongoDB Collection object


    • InsertOne
    • InsertOneAsync
    • InsertMany
    • InsertManyAsync
    • Insert
    useUpdateLink


    Expand
    titleUpdate Methods Supported

    UpdateManyAsync

    UpdateOneAsync

    UpdateOne

    UpdateMany

    ReplaceOne

    ReplaceOneAsync

    Update


     useSelectLink


    Expand
    titleSelect Methods Supported

    Find

    FindSync

    FindAsync

    FindOne

    FindOneAs

    Exists

    FindOneAndDelete

    FindOneAndDeleteAync

    FindOneAndReplace

    FindOneAndReplaceAsync

    FindOneAndUpdate

    FinOneAndUpdateAsync

    FindAllAs

    FindAll

    FindOneByIdAs

    BulkWrite

    BulkWriteAsync


    useDeleteLink 


    Expand
    titleDelete Method Supported

    DeleteMany
    DeleteManyAsync
    DeleteOne
    DeleteOneAsync
    FindOneAndDelete
    FindOneAndDeleteAsync

    Remove


    Amazon DocumentDB Identification

    The below mentioned objects have properties to indicate whether the object is of type MongoDB or Amazon DocumentDB.

    Object

    Property Description

    Type of Property Value

    Possible Value(s)

    Meaning

    DotNet MongoDB collectionIs an Amazon DocumentDB collection?Integer

    1



    The collection object is of type Amazon DocumentDB

    0The collection object is of type MongoDB
    DotNet unknown MongoDB collectionIs an Amazon DocumentDB collection?Integer

    1




    The collection object is of type Amazon DocumentDB

    0The collection object is of type MongoDB


    What results can you expect?

    Once the analysis/snapshot generation has completed, you can view the results in the normal manner (for example via CAST Enlighten). Some examples are shown below.

    ...

    Database and Collection Creation

    ...

    Expand
    titleDatabase and Collection


    Code Block
    languagec#
    titleDatabase and Collection
    public
    static void 
    Aggregate
    InsertOneInMongoDB()
           
    
            {
    
                var agbrands
            
                MongoClient client = new MongoClient(
    ).GetDatabase("Banks").GetCollection<BsonDocument>("albarakacomtr_FollowerTweet") .Aggregate().Group(
    "mongodb://127.0.0.1:27017");
              
         
    new
     
    BsonDocument
     
    {
     
    {
     
    "_id",
     
    "$url.expanded_url"
     
    },                   
     
    { "count", new BsonDocument("$sum", 1) } }).ToListAsync().Result;          }

    Image Removed

    IMongoDatabase db = client.GetDatabase("TestDb1");
         
                IMongoCollection<Person> persons = db.GetCollection<Person>("Persons");
                IMongoCollection<Dog> dogs = db.GetCollection<Dog>("Dogs");
    }

    Image Added

    Insert Operation

    Expand
    titleInsert operation


    Code Block
    languagec#
    titleInsert
    public void InsertBson() { MongoDB.Driver.MongoClient mc
    {
                MongoClient client = new 
    MongoDB.Driver.MongoClient();         var
    MongoClient("mongodb://127.0.0.1:27017");
                IMongoDatabase db = 
    mc
    client.GetDatabase("
    Test
    TestDb1");
            var col
    
                IMongoCollection<BsonDocument> dogs = db.GetCollection<BsonDocument>("
    Brand
    Dogs");
    
        
            var
     
    brand
     
    =
     
    new
     
    BsonDocument
     
    {
     
    {
     
    "Id",
     
    2
    string 
    },
    json 
    {
    = "{Name
    ", "test" } };         col.InsertOne(brand); }

    ...

    :'大黄',Age:10,Weight:50}";
                BsonDocument d1 = BsonDocument.Parse(json);//解析Json数据
                dogs.InsertOne(d1);
    
    }

    Image Added

    Delete Operation

    Expand
    titleDelete Operation


    Code Block
    languagec#
    titleDelete
     public void DeleteAllPurchases()
            {
                MyShoppingCollection.DeleteMany(FilterDefinition<PurchaseBson>.Empty, null);
            }

    Image Added

    Select Operation

    ...

    Expand
    titleSelect Operation


    Code Block
    titleDelete
    public PurchaseBson[] FindPurchases()
            {             MongoClient mc = new MongoClient();             var db = mc.GetServer().GetDatabase("Test");             var col = db.GetCollection<Brand>("Brand");             var filt = Builders<Brand>.Filter.Eq("Id", 1);             col.DeleteOne(filt);         }

    Image Removed

    
            {
                var purchases = MyShoppingCollection.Find(FilterDefinition<PurchaseBson>.Empty, null).ToList();
                return purchases.ToArray();
            }

    Image Added

    Update Operation

    Expand
    titleUpdate Operation


    Code Block
    languagec#
    titleUpdate
     public async Task<IActionResult> Update()
            {
                var query = from k in (from a in _context.Books.AsQueryable()
                                        where a.Title == "Test Book 2"
                                        from b in a.Posts
                                        select b)
                             where k.Title == "Second One"
                             select k;
                var result = await query.FirstOrDefaultAsync();
                result.ReadCount = 5;
    
                _context.Books
                    .FindOneAndUpdate(x => x.Title == "Test Book 2" && x.Posts.Any(p => p.Title == "Second One"),
                                        Builders<Book>.Update.Set(x => x.Posts[-1], result));
    
                return Redirect("/");
            }
    
    

    Image Added



    Amazon DocumentDB Identification

    ...

    Expand
    titleAmazon DocumentDB Identification


    public
    Code Block
    languagec#
    title
    Select
    Sample Code
    class Program
        {
           static void 
    Read
    Main(string[] args)
            {             MongoDB.Driver.MongoClient mc = new MongoDB.Driver.MongoClient();             var db = mc.GetDatabase("Test");             var col = db.GetCollection<Brand>("Brand");             var filter = Builders<Brand>.Filter.Eq("Id", 1);             var projection = Builders<Brand>.Projection.Include("Name");             var sort = Builders<Brand>.Sort.Descending("Name");             var brand = col.Find(filter).Project(projection).Sort(sort);         }

    Image Removed

    
            {
               string template = "mongodb://{0}:{1}@{2}/?replicaSet=rs0&readpreference={3}";
               string username = "root";
               string password = "rootroot";
               string clusterEndpoint = "sample-cluster.cluster-cqjaxx9hbhi0.us-west-2.docdb.amazonaws.com:27017";
               string readPreference = "secondaryPreferred";
    
               string connectionString = String.Format(template, username, password, clusterEndpoint, readPreference);
               var settings = MongoClientSettings.FromUrl(new MongoUrl(connectionString));
               var client = new MongoClient(settings);
    
               var database = client.GetDatabase("library");
               var collection = database.GetCollection<BsonDocument>("Books");
    
               var docToInsert = new BsonDocument { { "title", "Harry Potter" } };
               collection.InsertOne(docToInsert);
            }
        }
    
    

    Image Added


    Reading Database and Collection from Json File

    Update
    Expand
    titleReading Database and collection through Json files


    Code Block
    languagec#
    title
    .cs code
     public
    void Update()         {             MongoClient mc
     class CustomerService
        {
            private readonly IMongoCollection<Customer> _customer;
            private readonly DeveloperDatabaseConfiguration _settings;
    
            public CustomerService(IOptions<DeveloperDatabaseConfiguration> settings)
            {
                _settings = settings.Value;
                var client = new MongoClient(_settings.ConnectionString);
               
    
                var 
    db3
    database = 
    mc
    client.GetDatabase(
    "Test");             var col
    _settings.DatabaseName);
                _customer = 
    db3
    database.
    GetCollection<Brand>("Brand");             var filt = Builders<Brand>.Filter.Eq("Id", 1);             var upd = Builders<Brand>.Update.Set("Name", "Test1");             col.UpdateManyAsync(filt, upd).Wait();         }

    Image Removed

    Violations in AED

    Image Removed

    Evolution

    • Previously, only files consisting of relevant MongoDB imports were processed further for analysing.
    • Support has been evolved to process a file when it does not contain MongoDB import but makes use of its methods (APIs). Assumption here is file makes use of same namespace as used in the file containing MongoDB imports.

    Limitations

    • Connection, database and collection names are resolved as known objects only in the following situations:
      • Name is hardcoded
      • Name is defined in the variable in the local method
      • Name is defined in the config files
    • Only files consisting of relevant MongoDB imports are processed further for analysing. In a case, where a file uses reference of another file / namespace which in turn uses relevant import, then file will not be analysed.

    Future Development

    ...

    GetCollection<Customer>(_settings.CustomerCollectionName);
            }
    
            public async Task<List<Customer>> GetAllAsync()
            {
                return await _customer.Find(c => true).ToListAsync();
            }
        }
    
    


    Code Block
    languagec#
    title.cs file
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    
    namespace WorkingWithMongoDB.WebAPI.Configuration
    {
        public class DeveloperDatabaseConfiguration
        {
            public string CustomerCollectionName { get; set; }
            public string ConnectionString { get; set; }
            public string DatabaseName { get; set; }
        }
    }
    
    


    Code Block
    titleJson file
    {
      "DeveloperDatabaseConfiguration": {
        "CustomerCollectionName": "Customers",
        "ConnectionString": "mongodb://localhost:27017",
        "DatabaseName": "DevelopmentDatabase"
      },
      "Logging": {
        "LogLevel": {
          "Default": "Information",
          "Microsoft": "Warning",
          "Microsoft.Hosting.Lifetime": "Information"
        }
      },
      "AllowedHosts": "*"
    }

    Image Added


    Violations in CAST Engineering Dashboard

    The CAST Engineering Dashboard recognises code violations in source applications.

    Image Added

    Evolution

    • Database and collection objects are resolved in maximum cases
    • Support for all crud links for the library Mongodb.driver 
    • Reading database and collection values through JSON

    Limitations

    • Database and Collections are resolved in following situation: 
      • Anywhere in the .cs files  and JSON files
    • If Database and Collection values are not resolved, will create Unknown Database and Collection objects
    • Setting of properties related to Amazon DocumentDB identification depends on proper resolution of connection string.