Simple method to operate MongoDB with PHP (installation, addition, deletion, modification and query)

The examples in this article describe how to simply operate MongoDB with PHP. Share it with everyone for your reference, the details are as follows: If PHP operates MongoDB, first download the MongoDB expansion package from the Internet, https://github.com/mongodb/mongo-php-driver/downloads, and select the corresponding expansion package. I downloaded this and decompressed it. VC6 is suitable for apache, VC9 is suitable for IIS, and ts (thread safe) means that PHP runs in the form of a module. Then put the php_mongo.dll in the ext folder in PHP, then add extension=php_mongo.dll to PHP.INI and restart apache. Now the PHP extension MongoDB package is installed. For information on querying some MongoDB functions, please refer to the manual http://us.php.net/manual/en/class.mongocollection.php PHPDataBase; $collection = $db->PHPCollection; /*——————————– * delete *——————————– $collection->remove(array(“name” => “xixi111”)); */ /*——————————— * insert *——————————– for($i = 0;$i “xixi”.$i,”email” => “673048143_”.$i.”@qq.com”,”age” => $i*1+20); $collection->insert($data); } */ /*———————————- * Find *——————————– $res = $collection->find(array(“age” => array(‘$gt’ => 25,’$lt’ => 40)),array(“name” => true)); foreach($res as $v) { print_r($v); } */ /*———————————- * renew *——————————– $collection->update(array(“age” =>22),array(‘$set’ => array(“name” => “demoxixi”))); */ ?> Readers who are interested in more PHP-related content can check out the special topics of this site: “Complete of PHP + MongoDB database operation skills”,…

Golang uses json format to implement addition, deletion, and modification implementation examples

Requirements and ideas In a general small project or a small software, such as a small program such as a client, data persistence may be required. However, it is not suitable to use a general database (Mysql). Use embedding like sqlite3 The traditional method is a better method, but the sqlite3 library in Go language is in C language, and Cgo does not support cross-platform compilation. It is precisely because of this demand that I thought of using json format to save data directly in files. What is the specific idea? In Go language, if you want to convert data into json format, there are two formats: struct and map. If you need to add, delete, check and modify functions at the same time, it is more appropriate to use map as an intermediate format. . Next we will implement it. Query operation The implementation of this operation is relatively simple. Just read the data in the file directly and use the json library to deserialize it. The code is as follows: type Product struct { Name string `json:”name”` Num int `json:”num”` } func findAll() { ps := make([]Product, 0) data, err := ioutil.ReadFile(“./index.json”) if err != nil { log.Fatal(err)…

Detailed explanation of Django’s restful usage (built-in addition, deletion, modification and query)

What is rest REST is an architectural design guideline that all web applications should abide by. Representational State Transfer, translated as “presentation layer state transformation”. Resource-oriented is the most obvious feature of REST, a set of different operations for the same resource. A resource is a nameable abstract concept on the server. Resources are organized with nouns as the core. The first thing to focus on is the nouns. REST requires that various operations on resources must be performed through a unified interface. Only a limited set of operations can be performed on each resource. GET is used to obtain resources, POST is used to create new resources (can also be used to update resources), PUT (PATCH) is used to update resources, and DELETE is used to delete resources. api definition specification http://xxx.com/api/ Resources In the RESTful architecture, each URL represents a resource, so the URL cannot have verbs, only nouns, and the nouns used often correspond to the table names of the database. Generally speaking, the tables in the database are “collections” of the same type of records, so the nouns in the API should also be pluralized. For example, if there is an API that provides zoo information,…

Java connects to Mongodb to implement addition, deletion, modification and query

The example in this article shares with you the specific code for connecting java to Mongodb to implement addition, deletion, modification and query for your reference. The specific content is as follows 1. Create a maven project org.mongodb mongodb-driver 3.4.1 2. Write code 1. Query all package com.czxy.mongodb; import com.alibaba.fastjson.JSON; import com.mongodb.*; import java.util.List; import java.util.Set; public class Find { public static void main(String[] args) { //Client link MongoClient mOngodbClint= new MongoClient(“localhost”, 27017); // Get all databases List databaseNames = mongodbClint.getDatabaseNames(); for (String databaseName : databaseNames) { System.out.println(“Database Name “+databaseName); } //Connect to the specified database DB db = mongodbClint.getDB(“text”); //Get all collection names under the current database Set collectiOnNames= db.getCollectionNames(); for (String dbname : collectionNames) { System.out.println(“Collection name “+dbname); } // Connect to the specified collection DBCollection collection = db.getCollection(“stus”); //Data collection information DBCursor dbObjects = collection.find(); while (dbObjects.hasNext()){ //Read data DBObject next = dbObjects.next(); // json format conversion Stus parse = JSON.parseObject(next.toString(), Stus.class); // data output System.out.println(parse); } } } 2. Add data package com.czxy.mongodb; import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; import java.util.HashMap; import java.util.Map; public class Insert { public static void main(String[] args) { // Get connection MongoClient mOngodbClint= new MongoClient(“localhost”, 27017); // Connect to…

PHP operates MongoDB to implement addition, deletion, modification and query functions [Attached is the method of operating MongoDB in php7]

The example in this article describes how PHP operates MongoDB to implement the add, delete, modify, and query functions. Share it with everyone for your reference, the details are as follows: MongoDB’s PHP driver provides some core classes to operate MongoDB. Generally speaking, it can implement all the functions in the MongoDB command line, and the parameter formats are basically similar. The operations of MongoDB between versions before PHP7 and after PHP7 are different. This article mainly uses the previous version of PHP7 as an example to explain the various operations of PHP on MongoDB. Finally, it briefly explains the operations of MongoDB by versions after PHP7. 1. Data insertion //insert() //Parameter 1: an array or object //Parameter 2: Extended options // fsync: The default is false. If it is true, mongo will force the data to be written to the hard disk before confirming that the data is inserted successfully. // j: The default is false. If it is true, mongo will force the data to be written to the log before confirming that the data insertion is successful. // w: The default is 1. The write operation will be confirmed by the (main) server. If it is 0,…

014GoWeb tests pg addition, deletion, modification and check

1:data/data.go package data import( “fmt” “database/sql” _”github.com/lib/pq” ) const( host = “192.168.72.128” port = 5432 user = “test” password = “test” dbname = “testdb” ) var Db *sql.DB func init(){ var err error pgInfo := fmt.Sprintf(“host=%s port=%d user=%s password=%s dbname=%s sslmode=disable”, host, port, user, password, dbname) Db, err = sql.Open(“postgres”, pgInfo) if err != nil{ panic(err) } } 2: post/post.go package post import( .”Chapter10/data” ) type Post struct{ ID int `json:”id”` Content string `json:”content”` Author string `json:”author”` } func (post *Post) AddPost()(err error){ sql := “insert into post(content,author) values($1,$2) returning id” stmt, err:= Db.Prepare(sql) if err != nil{ return } defer stmt.Close() err = stmt.QueryRow(post.Content, post.Author).Scan(&post.ID) return } func (post *Post) DelPost()(err error){ sql := “delete from post where id=$1” _,err = Db.Exec(sql, post.ID) return } func (post *Post) EditPost()(err error){ sql:= “update post set cOntent=$1 where id=$2” _,err = Db.Exec(sql, post.Content, post.ID) return } func FindPost(id int)(err error, post Post){ sql := “select id, content, author from post where id=$1” post = Post{} err = Db.QueryRow(sql, id).Scan(&post.ID, &post.Content, &post.Author) return } 3:main.go package main import( “encoding/json” “net/http” “path” “strconv” “time” .”Chapter10/post” ) type Result struct{ No int `json:”no”` Msg string `json:”msg”` Obj interface{} `json:”obj,omitempty”` Time time.Time `json:”response_time”` } func…

Introduction to MongoDB, installation, additions, deletions and modifications

Introduction to MongoDB, installation, addition, deletion, modification and query

What the hell is MongoDB? Recently, too many students have mentioned MongoDB to me. They want to learn MongoDB, but they still don’t know what MongoDB is. In other words, they know it is a database or a file database, but they don’t know how to use it. That’s great, it’s said that it only comes out after a thousand calls, I’ll show it to you now: 1. First introduction to MongoDB: Everything must start with theory, don’t you think? MongoDB is a database based on distributed file storage. Written in C++ language. Designed to provide scalable, high-performance data storage solutions for WEB applications. MongoDB 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. The official explanation is given above, so to sum up, Mader F U C K! There is too little effective information (completely useless) So let me tell you about MongoDB in human language The biggest difference between it and the relational database we use is the constraint. It can be said that there is almost no constraint in the file database. In theory, there are no primary and…

Golangmap judgment, deletion

http://blog.sina.com.cn/s/blog_9e14446a01018q8p.html Map is a key-value relationship. Make is generally used to initialize memory, which helps reduce the number of memory allocations for subsequent new operations. If it is defined at the beginning but is not initialized with make, an error will be reported. package main import ( “fmt” ) func main(){ var test = map[string]string{“Name”:”李思”,”Gender”:”Male”} name,ok := test[“name”] // If the key exists, then name = Li Si, ok = true, otherwise, ok = false if ok{ fmt.Println(name) } delete(test,”name”)//Delete the value with the name key, it doesn’t matter if it does not exist fmt.Println(test) var a map[string]string a[“b”] = “c”//This will report an error, you must initialize the memory first a = make(map[string]string) a[“b”] = “c”//This will not be wrong }

python3 django mysql addition, deletion, modification and query

python3djangomysql addition, deletion, modification and query

Use Python’s django framework to connect to the database and operate the database code: import logging from django.db import connection LOG = logging.getLogger(“boss”) def dictfetchall(cursor): “Return all rows from a cursor as a dict” desc = cursor.description if desc ==None: return [] columns = [col[0] for col in desc] # for row in cursor.fetchall(): # rows.append(row) return [ dict(zip(columns, row)) for row in cursor.fetchall() ] def dictfetone(cursor): desc = cursor.description if desc ==None: returnNone columns = [col[0] for col in desc] row = cursor.fetchone() if row ==None: returnNone return dict(zip(columns,row)) def fetchall(sql,params=[]): cursor =connection.cursor() cursor.execute(sql,params) ret = dictfetchall(cursor) return ret def fetchone(sql,params=[]): cursor =connection.cursor() cursor.execute(sql,params) ret = dictfetone(cursor) cursor.close() return ret def executeDb(sql,params=[]): cursor =connection.cursor() ret = cursor.execute(sql,params) cursor.close() return ret You can see in the code that after the cursor is executed, close is executed. I wonder if Diango’s mysql connection does not have a connection pool? With this question in mind, I checked online and found that there is indeed documentation in this regard. Later, when I looked at the official website, I found: The latest version of Django already includes connection pooling, which can be controlled by modifying the configuration. Official documentation: https://docs.djangoproject.com/en/1.9/ref/databases/ The best proof is…

How to use addition, deletion, modification and query in Go microservice practice

How to use addition, deletion, modification and query in Go microservice practice

This article mainly introduces “How to use CRUD in Go microservice practice”. In daily operations, I believe many people have doubts about how to use CRUD in Go microservice practice. The editor has reviewed various information and sorted out simple and easy-to-use operation methods. I hope it will help everyone answer your doubts about “how to use addition, deletion, modification and search in Go microservice practice”! Next, please follow the editor to learn together! First, let’s start from the model layer and talk about the API and packaging details of go-zero. First, the APIs connected by the model layer are concentrated in core/stores. Let’s first take a look at operating databases such as mysql. For API methods, we come to core/stores/sqlx, so next we will use a few articles to give an overall introduction to The use and design ideas of sqlx. Quick use func main() { // 1 const datasource = “user:password@/dbname” mysqlDB := sqlx.NewMysql(datasource) // 2 um := model.NewUserModel(mysqlDB,”User”) // 3 ul := logic.NewUserLogic(um) // 4 engine.AddRoutes(nginxApi(ul)) engine.Start() } // NewUserModel, NewUserLogic similar func NewUserModel(conn sqlx.SqlConn, table string) *UserModel { return &UserModel{conn: conn, table: table} } // nginxApi injects logic into handle and binds routing and handler at…

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: 34331943@QQ.com

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
首页
微信
电话
搜索