Add, delete, modify, and query array elements and embedded documents in the MongoDB database

For example, I have a user class, which contains a label attribute. This label is an array, and the elements in the array are embedded documents. The format is as follows: { “_id” : “195861”, “tags” : [                                               { “tagId” : NumberLong(766), “optDate” : ISODate(“2013-08-12T15:21:02.930Z”), “enable” : true               },                                               { “tagId” : NumberLong(778), “optDate” : ISODate(“2013-08-12T15:21:02.930Z”), “enable” : true           } ] } Next, add, delete and check tags in this document. Spring mongodb is used here. MongoTemplate class inside. Here I abstract the embedded documents in tags into the Tag class. Code deletion and modification itself contains query methods, so no query methods are written. /** * * @author zhangdonghao * */ @Component(“UserrTagServiceImpl”) public class UserrTagServiceImpl implements UserrTagService { /** * Mongo DB Spring Template */ @Resource protected MongoTemplate mOngoTemplate= null; public UserrTagServiceImpl() { } /** **Add an element to the tags array */ @Override public Response addTag(String id, Long tagId) { Try { Tag tag = new Tag(tagId);         tag.setOptDate(new Date());         tag.setEnable(true); Query query = Query.query(Criteria.where(“_id”).is(id)); Update update = new Update(); ​ ​ update.addToSet(“tags”, tag); mongoTemplate.upsert(query, update, User.class); } catch (Exception e) { Return new Response(0); } Return new Response(1); }…

MongoDB add, delete, modify

Introduction to MongoDB driver types 1. MongoDB official driver: mongo-csharp-driver, download address: https://github.com/mongodb/mongo-csharp-driver/downloads 2. Third-party driver samus , this is a frequently used driver with a relatively fast update frequency. In addition to supporting general operations, the samus driver also supports Linq Introduction to MongoDB driver types 1. MongoDB official driver: mongo-csharp-driver, download address: https://github.com/mongodb/mongo-csharp-driver/downloads 2. The third-party driver samus is a commonly used driver with a relatively fast update frequency. In addition to supporting general operations, the samus driver also supports Linq and Lambda expressions. Download address: https://github.com/samus/mongodb-csharp. The operation process of the two mongodb drivers on the mongodb database is basically the same, but there are differences in the implementation methods. For example, the samus driver not only supports general formal operations, but also supports Linq and Lambda expressions. Use MongoDB official driver to operate the database Unzip the package and get the following two files: MongoDB.Bson.dll: Serialization, Json related MongoDB.Driver.dll: mongodb driver Add references and introduce the above two DLLs into the project Introducing namespaces into code using MongoDB.Bson; using MongoDB.Driver; Obtain database connection service string cOnnectionString= ” mongodb://localhost ” ; //mongodb://[username:password@]hostname[:port][/[database][?options]] MongoServer server = MongoServer.Create(connectionString); // Connect to a MongoServer Get a reference to the specified…

Detailed examples of operating MongoDB database with PHP (add, delete, modify, check) (6)

PHP operates mongodb: PHP needs to install modules to operate mongodb The official website can be downloaded: http://pecl.php.net/package/mongo download mongodb Set the startup mode to user authorization The php manual does not have some user authorization methods to log in: conn.php <?php $cOnn= new Mongo( “mongodb://user1:123456@localhost:27017/test”); //User authorization to link to mongodb test database $db = $conn->test; ?> find.php <?php include “conn.php”; $c1 = $db->c1; //Operation c1 collection / /Because json cannot be used directly in php //db.c1.find({name:”user1″}); cannot be played like this //{name:”user1″} == array(” name”=>”user1″) use this form //[1,2] == array(1,2); //{} == array() $arr=array(); $rst = $c1->find($arr); foreach($rst as $val){ echo “ ” ; print_r($val[‘name’]); //If you get the id, you get “_id” } Example 2: Query by specified value /> $arr = array(“name”=>”user1″); //Query nam=user1 $rst = $c1->find($arr); foreach($rst as $val){ echo ” “; $fis = $val[‘_id’]; print_r($val); echo “”; // You will find that fid becomes a string when passed to user.php. How to solve it? //user.php Check the data corresponding to mongodb according to _id <?php include “conn.php”; $c1 = $db->c1; /> $oid= new MongoId($_GET[‘fid’]); Use this to convert var_dump($oid); //It is still Object, otherwise it will be string type $arr = array(“_id”=>”$oid”); $rst…

MongoDB add, delete, modify

Introduction to MongoDB driver types 1. MongoDB official driver: mongo-csharp-driver, download address: https://github.com/mongodb/mongo-csharp-driver/downloads 2. Third-party driver samus , this is a frequently used driver with a relatively fast update frequency. In addition to supporting general operations, the samus driver also supports Linq Introduction to MongoDB driver types 1. MongoDB official driver: mongo-csharp-driver, download address: https://github.com/mongodb/mongo-csharp-driver/downloads 2. The third-party driver samus is a commonly used driver with a relatively fast update frequency. In addition to supporting general operations, the samus driver also supports Linq and Lambda expressions. Download address: https://github.com/samus/mongodb-csharp. The operation process of the two mongodb drivers on the mongodb database is basically the same, but there are differences in the implementation methods. For example, the samus driver not only supports general formal operations, but also supports Linq and Lambda expressions. Use MongoDB official driver to operate the database Unzip the package and get the following two files: MongoDB.Bson.dll: Serialization, Json related MongoDB.Driver.dll: mongodb driver Add references and introduce the above two DLLs into the project Introducing namespaces into code using MongoDB.Bson; using MongoDB.Driver; Obtain database connection service string cOnnectionString= ” mongodb://localhost ” ; //mongodb://[username:password@]hostname[:port][/[database][?options]] MongoServer server = MongoServer.Create(connectionString); // Connect to a MongoServer Get a reference to the specified…

Examples of Django database operations (add, delete, modify, check)

Create a table in the database class Business(models.Model): #Automatically create ID column caption = models.CharField(max_length=32) code = models.CharField(max_length=32) 1. Add Method 1 models.Business.objects.create(caption=’Marketing Department’,code=’123′) Method 2 obj = models.UserInfo(caption=’Marketing Department’,code=’123′) obj.save() Method 3 dic = {‘caption’:’Marketing Department’,’code’:’123′} models.Business.objects.create(**dic) 2. Delete models.Business.objects.filter(id=1).delete() For the query method, please see the query below 3. Change Method 1 models.Business.objects.filter(id=1).update(code=’hello’) Method 2 obj = models.Business.objects.get(id=1) obj.code = ‘hello’ obj.save() For the query method, please see the query below 4. Query Get all v1 = models.Business.objects.all() #QuerySet type, internal elements are all objects Get specified v2 = models.Business.objects.all().values(“id”,”caption”) #QuerSet type, internal elements are all dictionaries v3 = models.Business.objects.all().values_list(‘id’,’caption’) #QuerySet type, internal elements are tuples v4 = models.Business.objects.get(id=1) #Get a team object and report an error if it does not exist v5 = models.Business.objects.filter(id=1) #QuerySet type, internal elements are objects, id__gt=1 gets all data with id>1, id__lt=10, gets all data with id<10 v6 = models.Business.objects.filter(id=1).first() #Return object or None Application examples business function def business(request): v1 = models.Business.objects.all() v2 = models.Business.objects.all().values(“id”,”caption”) v3 = models.Business.objects.all().values_list(‘id’,’caption’) return render(request,”business.html”,{“v1″:v1,”v2″:v2,”v3”:v3}) url(r’^business$’,views.business) business.html ALL {% for row in v1 %} {{row.id}}-{{row.caption}}-{{row.code}} {% endfor %} all.values {% for row in v2 %} {{row.id}}-{{row.caption}} {% endfor %} all.values_list {% for row in v3 %}…

Go language dictionary (map) usage example analysis [create, fill, traverse, search, modify, delete]

The examples in this article describe the usage of Go language dictionary (map). Share it with everyone for your reference, the details are as follows: A dictionary is a built-in data structure that holds an unordered collection of key-value pairs. (1) Creation of dictionary 1) make(map[KeyType]ValueType, initialCapacity) 2) make(map[KeyType]ValueType) 3) map[KeyType]ValueType{} 4) map[KeyType]ValueType{key1 : value1, key2 : value2, … , keyN : valueN} As follows, four methods are used to create arrays. The difference between the first and second methods is whether the initial capacity is specified. However, you do not need to care about this when using it, because the nature of map determines it. Once the capacity is insufficient, it will automatically expand: The code is as follows: func test1() { Map1 := make(map[string]string, 5) Map2 := make(map[string]string) Map3 := map[string]string{} map4 := map[string]string{“a”: “1”, “b”: “2”, “c”: “3”} fmt.Println(map1, map2, map3, map4) } Output: map[] map[] map[] map[c:3 a:1 b:2] (2) Dictionary filling and traversal: for range The code is as follows: func test2() { Map1 := make(map[string]string) Map1[“a”] = “1” Map1[“b”] = “2” Map1[“c”] = “3” For key, value := range map1 {               fmt.Printf(“%s->%-10s”, key, value) } } As above, the array is filled using…

Detailed tutorial on operating MongoDB in Python (insert, check, modify, sort, delete)

Catalogue Insert document Insert collection Return the _id field Insert multiple documents Insert multiple documents with the specified _id Query documents Query a piece of data Query all the data in the collection Query the data in the specified field Query according to the specified conditions Advanced query Return the specified number of records Modify the document Sort Delete data Delete multiple documents Delete from collection All documents Delete collection MongoDB is a database based on distributed file storage. It is a product between a relational database and a non-relational database. It is the most feature-rich among non-relational databases and is most similar to a relational database. MongoDB is one of the most popular NoSQL databases, using the data type BSON (similar to JSON). First you need to install MongoDB, the installation process will not be described in detail Then Python needs the MongoDB driver to connect to MongoDB, install it with pip pip install pymongo Insert document A document in MongoDB is similar to a record in a SQL table. Insert collection Insert documents into the collection using the insert_one() method. The first parameter of this method is a dictionary name => value pair. Example: Insert documents into the…

Does anyone have a Django add, delete, modify, check project? If you have done it, please send it to me.

Who has a Django add, delete, modify, check project? If you have done it, send it to me update html: urls.pyurlpatterns = patterns(”,(‘^area_update/$’, area_update),)models.pyclass Area(models.Model): val = models.CharField(max_length=255, blank=True, null=True)views.pydef area_update(request): id = request.REQUEST.get(‘id’) val = request.REQUEST.get(‘val’) area = Area.objects.get(id=id) area.val = val area.save() return HttpResponse(“ok”)Python is the language and django is the framework. How does Django display the contents of the database in admin How to do it: First, run the python manage.py createsuperuser command to create an administrator account. Then enter /admin in the URL to reach the administrator login page. After logging in, you will find that there are no items to be displayed in the database because we have not registered yet. Next we register the data model to be managed in admin; register the model in admin.py. Then refresh the page and you will see the ContactMessage data table. You can add and delete in it for simple addition, deletion, modification and query. How to create a Django website This article demonstrates how to create a simple Django website. The Django version used is 1.7. 1. Create a project. Run the following command to create a Django project. The project name is mysite: $ django-admin.py…

ORM’s *add, delete, modify, and check* operations on the database in Django

Foreword What is an ORM? ORM (Object Relational Mapping) refers to using object-oriented methods to handle operations such as creating tables in the database and adding, deleting, modifying, and querying data. A table in the database = a class. Each record in the database = an object. In short, defining a class in Django is to create a table in the database. Instantiating an object of a class in Django adds a record to the database. Deleting an object in Django deletes a record in the database. Changing the properties of an object in DJango is to modify the value of a record in the database. Traversing the attribute values ​​of the query object in Django is to query the value of the record in the database. The following are several command statements in Django’s views function. One, increase (create, save) from app01.models import * #Create method one: Author.objects.create(name=\’Alvin\’) #Create method two: Author.objects.create(**{“name”:”alex”}) #save method one: author=Author(name=”alvin”) author.save() #Save method two: author=Author() author.name=”alvin” author.save() Two, delete >>> Book.objects.filter(id=1).delete() (3, {\’app01.Book_authors\’: 2, ​​\’app01.Book\’: 1}) If it is a many-to-many relationship: remove() and clear() methods: #Forward book = models.Book.objects.filter(id=1) #Delete all related information associated with girl 1 in the third table book.author.clear()…

MongoDB add, delete, modify, query operation mongoose verification + set association

MongoDB add, delete, modify, query operation mongoose verification + set association

mongoose verification When creating a collection rule, you can set the validation rules for the current field. If validation fails, insert failure will be entered Commonly used validation rules provided within mongoose: required: true required field or [ true , ‘ Please enter ×× ‘ ] minlength: Minimum length of string maxlength Maximum length of string (error message can also be customized) trim: remove spaces on both sides of the string min: 2 The minimum value is 2 max: 100 The maximum value is 100 default: default value enum: enumerates the values ​​that the current field can have Custom validator: validate: custom validator set association Usually there is a relationship between data in different collections. For example, article information and user information are stored in different collections, but the article is published by a user. To query all the information of the article including the publishing user, just Need to use collection association Associate collections using ids Use the populate method to query related collections Collection association implementation Case: Add, delete, modify and check user information

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索