Represents a BSON document that can be used where an IMongoQuery is expected.
Наследование: BsonDocument, IMongoQuery
Пример #1
0
        public void Get_Foo_ByID()
        {
            #region Test setup
            MongoCollection<Foo> fooCollection = _database.GetCollection<Foo>(_collectionName);
            fooCollection.RemoveAll();
            BsonDocument fooDocEthan = new BsonDocument {
                { "_id", _bobFooId },
                { "name", "Bob"}
            };
            BsonDocument fooDocAbby = new BsonDocument {
                { "_id", _hollyFooId },
                { "name", "Holly" }
            };

            fooCollection.Insert(fooDocEthan);
            fooCollection.Insert(fooDocAbby);
            #endregion

            QueryDocument query = new QueryDocument("_id", _bobFooId);
            Foo foo = fooCollection.FindOne(query);
            Assert.AreEqual(foo.Name, "Bob");

            #region Test cleanup
            fooCollection.RemoveAll();
            #endregion
        }
Пример #2
0
        public static IMongoQuery ParseQuery(string query)
        {
            var parsedQuery     = BsonDocument.Parse(query);
            var queryDocument   = new QueryDocument(parsedQuery);

            return queryDocument;
        }
Пример #3
0
        public static void SetStatus(BsonDocument service, bool restart)
        {
            try
            {
                var server = MongoServer.Create(ConfigurationManager.ConnectionStrings["mongodb"].ConnectionString);
                server.Connect();

                var database = server.GetDatabase("config");
                var collection = database.GetCollection("services");
                var filter = new QueryDocument { { "_id", service["_id"].AsObjectId } };
                var update = new UpdateDocument();

                foreach (var key in service)
                    update[key.Name] = key.Value;

                update["restart"] = restart;
                collection.Update(filter, update);

                server.Disconnect();
            }
            catch (Exception err)
            {
                Console.WriteLine("** error updating restart status: " + err.Message);
            }
        }
Пример #4
0
        //# Function to list of cars that are eligible for users request
        public List<Car> GetCars(InputRequestAttributes RequestQuery)
        {
            //# Get the list of zipcodes that are located in specified distance from user requested zipcode
            ConnectedRepository ctx = new ConnectedRepository(DbName);
            LocationDataLayer lctx = new LocationDataLayer();
            List<string> NearByZipCodes = new List<string>();
            if (!string.IsNullOrEmpty(RequestQuery.Zipcode))
            {
                List<Location> locationsAround = lctx.GetNearZipcodes(RequestQuery.Zipcode,RequestQuery.distance);
                if (locationsAround.Count != 0)
                {
                    foreach (Location location in locationsAround)
                    {
                        NearByZipCodes.Add(location.zip);
                    }
                    NearByZipCodes.Add(RequestQuery.Zipcode);
                }
            }
            //# Build a DB query based on user constraint. Check request if it has value and add it to query.
            QueryDocument CarQuery = new QueryDocument();

            if (RequestQuery.Year > 2000)
                CarQuery.Add("Year", RequestQuery.Year);
            if (RequestQuery.Name != null)
                CarQuery.Add("Name", RequestQuery.Name);
            if (RequestQuery.Maker != null)
                CarQuery.Add("Maker", RequestQuery.Maker);
            if (RequestQuery.MaxPrice >= 1000)
                CarQuery.Add("Price", new BsonDocument("$lt", RequestQuery.MaxPrice));
            if (NearByZipCodes.Count() != 0)
                CarQuery.Add("Zipcode", new BsonDocument("$in", new BsonArray(NearByZipCodes)));
            MongoCursor<Car> Cars = ctx.Cars.Find(CarQuery);
            List<Car> carsList = Cars.ToList();
            return carsList;
        }
        public Presence[] GetPresence(string from, string to, Matrix.Xmpp.PresenceType? type, bool remove)
        {
            List<Presence> presences = new List<Presence>();
            var db = GetDatabase();
            var collection = db.GetCollection("offline_presence");
            var query = new QueryDocument();
            if (from != null)
                query.Add("from", from);
            if (to != null)
                query.Add("to", to);
            if (type != null)
                query.Add("type", type.ToString());

            MongoCursor<BsonDocument> cursor;
            if (from == null && to == null)
                cursor = collection.FindAll();
            else
                cursor = collection.Find(query);

            foreach (var item in cursor)
            {
                Presence presence = (Presence)Presence.LoadXml(item.GetValue("value").AsString);
                presences.Add(presence);
            }
            if (remove)
                collection.Remove(query);
            return presences.ToArray();
        }
        // GET api/reportingrecord/5
        public HttpResponseMessage Get(string id, [FromBody]JObject JsonObject)
        {
            //Setup variables From Body
            JToken Project;
            JToken Oid;
            JToken Format;
            JToken userRole;

            JsonObject.TryGetValue("Project", out Project);
            JsonObject.TryGetValue("FormOid", out Oid);
            JsonObject.TryGetValue("Format", out Format);
            //just for POC, needs to be derived
            JsonObject.TryGetValue("Role", out userRole);

            if(Project==null ||Oid==null|| Format==null)
                return Request.CreateResponse(HttpStatusCode.BadRequest);
            userRole = userRole ?? 0;

            //Run Query against database and pull back records
            var query = new QueryDocument("project", Project.ToString());
            query.Add("FormOid", Oid.ToString());
            query.Add("DatabaseGuid", id);
            var ClinicalViews = CVCollection.Find(query);

            //Build Matrix from records and Create output
            switch(Format.ToString().ToLower())
            {
                case "csv":
                    return GetCsvOutput(ClinicalViews, int.Parse(userRole.ToString()));
                case "json":
                    return GetjsonOutput(ClinicalViews, int.Parse(userRole.ToString()));
                default:
                    return Request.CreateResponse(HttpStatusCode.NotImplemented);
            }
        }
Пример #7
0
        public Equipments FetchEquipments(string userid)
        {
            Equipments equipments = new Equipments();

            try
            {
                MongoServer server = MongoServer.Create(DbSettings.ConnectionString);
                MongoDatabase db = server.GetDatabase(DbConstants.DbNameGame, Credentials, new SafeMode(true));
                MongoCollection<BsonDocument> coll = db.GetCollection(DbConstants.CollectionNameEquipments);

                QueryDocument query = new QueryDocument("userid", userid);

                var cursor = coll.Find(query);

                foreach (BsonDocument item in cursor)
                {
                    string code = item["code"].AsString;
                    int count = item["count"].IsString ? Int32.Parse(item["count"].AsString) : item["count"].AsInt32;

                    equipments.Items.Add(code, count);
                }

                server.Disconnect();
            }
            catch (Exception ex)
            {
                log.Error("FetchEquipments: " + ex.ToString());
            }

            return equipments;
        }
Пример #8
0
        public bool Remove(Entity entity)
        {
            var queryDoc = new QueryDocument {{EntityIdName, entity.Id}};

            var result = Collection.Remove(queryDoc);
            return result.Ok;
        }
Пример #9
0
        public void TestMongoInteraction()
        {
            MongoServer server = MongoServer.Create();
            if (server.DatabaseExists(PropSetCollectionsDb))
                server.DropDatabase(PropSetCollectionsDb);
            MongoDatabase testDb = server.GetDatabase(PropSetCollectionsDb);
            if (testDb.CollectionExists("ut_collection"))
                testDb.DropCollection("ut_collection");

            MongoCollection<MongoPropertyElement> collection =
                testDb.GetCollection<MongoPropertyElement>("ut_collection");
            collection.EnsureIndex(IndexKeys.Ascending("Name"),IndexOptions.SetUnique(true));

            MongoPropertyElement el = new MongoPropertyElement("one");
            collection.Insert(el,SafeMode.True);
            collection.Insert(new MongoPropertyElement("two"),SafeMode.True);
            try
            {
                collection.Insert(new MongoPropertyElement("one"), SafeMode.True);
                Assert.Fail("Duplicate key insert");
            }
            catch(MongoSafeModeException ex)
            {

            }
            Assert.AreEqual(2, collection.Count());
            QueryDocument query=new QueryDocument("Name","one");
            MongoPropertyElement ee = collection.FindOne(query);
            Assert.IsNotNull(ee);
        }
Пример #10
0
 public void Fill(IPropertyPredicateOperator optr, QueryDocument doc)
 {
     switch (this.OpType)
     {
         case ExpressionType.Equal:
             optr.PutEqualPredicate(doc, this.Constant);
             break;
         case ExpressionType.NotEqual:
             optr.PutNotEqualPredicate(doc, this.Constant);
             break;
         case ExpressionType.GreaterThan:
             optr.PutGreaterThanPredicate(doc, this.Constant);
             break;
         case ExpressionType.GreaterThanOrEqual:
             optr.PutGreaterThanOrEqualPredicate(doc, this.Constant);
             break;
         case ExpressionType.LessThan:
             optr.PutLessThanPredicate(doc, this.Constant);
             break;
         case ExpressionType.LessThanOrEqual:
             optr.PutLessThanOrEqualPredicate(doc, this.Constant);
             break;
         default:
             throw new NotSupportedException();
     }
 }
Пример #11
0
        public static Equipments FetchEquipments(string userid)
        {
            Equipments equipments = new Equipments();

            try
            {
                MongoServer server = MongoServer.Create("mongodb://127.0.0.1:27017");
                MongoDatabase db = server.GetDatabase("Game", Credentials, new SafeMode(true));
                MongoCollection<BsonDocument> coll = db.GetCollection("Equipments");

                QueryDocument query = new QueryDocument("userid", userid);

                var cursor = coll.Find(query);

                foreach (BsonDocument item in cursor)
                {
                    string code = item["code"].AsString;
                    int count = item["count"].AsInt32;

                    equipments.Items.Add(code, count);
                }

                server.Disconnect();
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }

            return equipments;
        }
Пример #12
0
 //
 // GET: /ClinicalView/Details/5
 // Sample: http://localhost:64628/ClinicalView/details/6ea9c26ac9ea41ab9cb7483a00c8afcb9797528
 public ActionResult Details(string id)
 {
     var query = new QueryDocument("_id", id);
     var doc = CVCollection.FindOne(query);
     ViewBag.doc = doc.ToString();
     return View();
 }
 public void TestAndWithAll()
 {
     var all = new QueryDocument();
     var query = Query.And(all);
     var expected = "{ }";
     Assert.AreEqual(expected, query.ToJson());
 }
Пример #14
0
        static void Main(string[] args)
        {
            //连接信息
            string conn = "mongodb://localhost";
            string database = "demoBase";
            string collection = "demoCollection";
            MongoServer mongodb = MongoServer.Create(conn);
            //连接数据库
            MongoDatabase mongoDataBase = mongodb.GetDatabase(database);
            //选择数据库名
            MongoCollection mongoCollection = mongoDataBase.GetCollection(collection);
            //选择集合,相当于表
            mongodb.Connect();
            //普通插入
            var o = new { Uid = 123, Name = "xixiNormal", PassWord = "111111" };
            mongoCollection.Insert(o);
            //对象插入
            Person p = new Person { Uid = 124, Name = "xixiObject", PassWord = "222222" };
            mongoCollection.Insert(p);
            //BsonDocument 插入
            BsonDocument b = new BsonDocument();
            b.Add("Uid", 125);
            b.Add("Name", "xixiBson");
            b.Add("PassWord", "333333");
            mongoCollection.Insert(b);

            Console.WriteLine(mongoCollection.FullName);

            QueryDocument query = new QueryDocument();
            query.Add("Uid", 125);
            MongoCursor<Person> pers = mongoCollection.FindAs<Person>(query);
            //Console.WriteLine(pe.Name);
            Console.ReadLine();
        }
Пример #15
0
    public static User CheckUser(string id, string password)
    {
        MongoServer server = MongoServer.Create(connectionString);
        MongoDatabase db = server.GetDatabase(dbString);
        MongoCollection collection = db.GetCollection(collectionString);

        var query = new QueryDocument("StudentID", id);

        if(collection.Count(query)==0)
        {
            return null;
        }
        else
        {
             User result = collection.FindOneAs<User>(query);
             if(result.Password==HashMD5(password))
             {
                 return result;
             }
             else
             {
                 return null;
             }
        }
    }
Пример #16
0
        public dynamic find(MongoCollection collection,object[] args)
        {
            Type type = args[0].GetType();

            if(type.Name.Contains("<>__AnonType")){

                PropertyInfo[] properties = type.GetProperties();
                Dictionary<string,object> dictionary = new Dictionary<string, object>();
                foreach(var property in properties)
                    dictionary[property.Name] = property.GetValue(args[0],null);

                var query = new QueryDocument(dictionary);
                var result = collection.FindAs<BsonDocument>(query);
                List<Entity> documents = new List<Entity>();

                if(result.Size() > 0)
                {
                    foreach(var entity in result)
                        documents.Add(new Entity(entity));
                }

                return documents;
            }
            throw new NotImplementedException("Only annonymous types are accepted for Queries.");
        }
        public Message[] GetChatMessage(string user, bool delete)
        {
            if (string.IsNullOrEmpty(user))
                return null;

            user = user.ToLower();
            var db = GetDatabase();
            var collection = db.GetCollection("offline_msg");
            var query = from x in collection.AsQueryable<OfflineMessageItem>() where x.To == user select x;
            List<Message> msgs = new List<Message>();

            foreach (var item in query)
            {
                msgs.Add(new Matrix.Xmpp.Client.Message()
                {
                    From = item.From + "@gjtalk.com",
                    To = item.To + "@gjtalk.com",
                    Body = item.Body,
                    Delay = new Matrix.Xmpp.Delay.Delay(item.Time, item.From + "@gjtalkc.com"),
                    Type = (Matrix.Xmpp.MessageType)Enum.Parse(
                    typeof(Matrix.Xmpp.MessageType), item.MessageType)
                });
            }
            if (delete)
            {
                QueryDocument doc = new QueryDocument();
                doc.Add("To", user);
                collection.Remove(doc);
            }
            return msgs.ToArray();
        }
Пример #18
0
 public ActionResult Index()
 {
     Resume re = new Resume();
     QueryDocument query = new QueryDocument("resumeCode", "darylchymko1");
     re = _collection.FindOne(query);
     return View("Resume", re);
 }
 public int NumberCharactersOnServer(string region, string server)
 {
     QueryDocument query = new QueryDocument();
     query.Add("Server", server);
     query.Add("Region", region);
     return (int)Collection.Find(query).Count();
 }
    static void Main()
    {

      // Create seed data

      BsonDocument[] seedData = CreateSeedData();

      // Standard URI format: mongodb://[dbuser:[email protected]]host:port/dbname

      String uri = "mongodb://user:[email protected]:port/db";
      
      MongoUrl url = new MongoUrl(uri);
      MongoClient client = new MongoClient(url);
      MongoServer server = client.GetServer();
      MongoDatabase db = server.GetDatabase(url.DatabaseName);
      
      /*
       * First we'll add a few songs. Nothing is required to create the
       * songs collection; it is created automatically when we insert.
       */
      
      var songs = db.GetCollection<BsonDocument>("songs");

       // Use Insert for single BsonDocument insertion.

      songs.InsertBatch(seedData);

      /*
       * Then we need to give Boyz II Men credit for their contribution to
       * the hit "One Sweet Day".
       */
    
      QueryDocument updateQuery = new QueryDocument{ { "Title", "One Sweet Day" } };

      songs.Update(updateQuery, new UpdateDocument{ { "$set", new BsonDocument( "Artist", "Mariah Carey ft. Boyz II Men") } });

      /*
       * Finally we run a query which returns all the hits that spent 10 
       * or more weeks at number 1.
       */

      QueryDocument findQuery = new QueryDocument{ { "WeeksAtOne", new BsonDocument{ { "$gte", 10 } } } };
      var cursor = songs.Find(findQuery).SetSortOrder(SortBy.Ascending("Decade"));
      
      foreach (var song in cursor) 
      {
        var test = song["Decade"];
        Console.WriteLine("In the {0}, {1} by {2} topped the charts for {3} straight weeks",
          song["Decade"], song["Title"], song["Artist"], song["WeeksAtOne"]);
      }

      // Since this is an example, we'll clean up after ourselves.

      songs.Drop();

      // Only disconnect when your app is terminating.

      server.Disconnect();
    }
Пример #21
0
 public void ClearCategories(Models.TextContent content)
 {
     //((IPersistable)content).OnSaving();
     MongoCollection<BsonDocument> collection = content.GetRepository().GetCategoriesCollection();
     var query = new QueryDocument { { "ContentUUID", content.UUID } };
     collection.Remove(query);
     //((IPersistable)content).OnSaved();
 }
Пример #22
0
 public bool Delete(dynamic lookup)
 {
     var _qs = lookup.query as string;
     var _query = new QueryDocument(new BsonDocument().FromJson(_qs));
      var _coll = _db.GetCollection(lookup.collection);
     var res = _coll.Remove(_query);
     return res.Ok;
 }
 public void TestAndWithAllOnRight()
 {
     var left = Query<Entity>.EQ(x => x.Name, "John");
     var all = new QueryDocument();
     var query = Query.And(left, all);
     var expected = "{ 'Name' : 'John' }".Replace("'", "\"");
     Assert.AreEqual(expected, query.ToJson());
 }
Пример #24
0
 public void Delete(Models.TextContent content)
 {
     var database = content.GetRepository().GetDatabase();
     MongoCollection<BsonDocument> collection = database.GetCollection(content.GetSchema().GetSchemaCollectionName());
     var query = new QueryDocument { { "UUID", content.UUID } };
     collection.Remove(query);
     TextContentFileHelper.DeleteFiles(content);
 }
 public IList<Character> GetCharactersInGuild(string region, string server, string guild)
 {
     QueryDocument query = new QueryDocument();
     query.Add("Server", server);
     query.Add("Region", region);
     query.Add("Guild", guild);
     return Collection.Find(query).OrderBy(c => c.CurrentPoints).ToList();
 }
Пример #26
0
        public Subscriber GetSubscriber(string deviceId)
        {
            var coll = _database.GetCollection<Subscriber>(SubscribersKey);
            var query = new QueryDocument("DeviceId", deviceId);
            var subscriber = coll.FindOne(query);

            return subscriber;
        }
 public void TestTryMapToBsonValueWithQueryDocument()
 {
     var query = new QueryDocument("x", 1);
     BsonValue bsonValue;
     var ok = BsonTypeMapper.TryMapToBsonValue(query, out bsonValue);
     Assert.AreEqual(true, ok);
     Assert.AreSame(query, bsonValue);
 }
Пример #28
0
 /// <summary>
 /// 创建一个Between关系的过滤条件
 /// </summary>
 /// <param name="field"></param>
 /// <param name="value1"></param>
 /// <param name="value2"></param>
 /// <returns></returns>
 public static MongoDBFilter Between(string field, object value1, object value2)
 {
     Dictionary<string, object> dict = new Dictionary<string, object>();
     dict.Add("$gte", value1);
     dict.Add("$lte", value2);
     QueryDocument doc = new QueryDocument(dict);
     return new MongoDBFilter(new QueryDocument(field, doc));
 }
Пример #29
0
 public bool Delete(dynamic lookup)
 {
     var _qs = lookup.ids as string;
     string query = String.Concat("{ \"_id\":", "{ \"$in\": " + _qs + " } }");
     var _query = new QueryDocument(BsonSerializer.Deserialize<BsonDocument>(query));
     var _coll = _db.GetCollection(lookup.collection.ToString());
     _coll.Remove(_query);
     return true;
 }
        public void addAlert2UserTest()
        {
            WellCastServerEngine mm = new WellCastServerEngine();

            User user = new User();

            user.ID = "542c53a302d6a4910db3fdd7";
            BsonArray forecastIDs = new BsonArray();

            string id1 = Guid.NewGuid().ToString();
            string id2 = Guid.NewGuid().ToString();

            forecastIDs.Add(id1);
            forecastIDs.Add(id2);

            MongoDatabase mdb;
            //Get a Reference to the Client Object
            var mongoClient = new MongoClient("mongodb://pelustondo:[email protected]:41140/wellcast");
            var mongoServer = mongoClient.GetServer();
            mdb = mongoServer.GetDatabase("wellcast");

            var queryDoc2 = new QueryDocument { { "state", "unsent" } };
            // Query the db for a document with the required ID
            var alertsUnSent0 = mdb.GetCollection("alerts").Find(queryDoc2);
            long alerts0 = alertsUnSent0.Count();

            mm.addAlert2User(user, forecastIDs);

            var alertsUnSent1 = mdb.GetCollection("alerts").Find(queryDoc2);
            long alerts1 = alertsUnSent1.Count();

            Assert.AreEqual(alerts1, alerts0 + 1);
        }