検索

mongodb update 数组 操作

Jun 07, 2016 pm 04:37 PM
mongodbupdate操作する配列記事

前一篇文章说到了mongodb update 的字符操作,下面说一下mongodb update的数组操作,用的版本是mongodb2.6.3。 一,$美元符号,在update中,可理解为数组下标 例1 db.students.insert( //插入测试数据 [ {"_id" :6, "grades" : [ 80, 85, 90 ],"score":[10,4

前一篇文章说到了mongodb update 的字符操作,下面说一下mongodb update的数组操作,用的版本是mongodb2.6.3。

一,$美元符号,在update中,可理解为数组下标

例1

db.students.insert(       //插入测试数据
 [
 {"_id" :6, "grades" : [ 80, 85, 90 ],"score":[10,40,54]},
 {"_id" :7, "grades" : [ 88, 90, 92 ],"score":[100,30,51]}
 ]
);
//把满足score大于90的grades,数组的第一个元素设置成88
db.students.update(  { score: {$gt:90} },
            { $set: { "grades.$" : 88 } } ,
            { multi:true }
             );

相同功能php代码:

$where = array("score"=>array('$gt'=>70));
$param = array('$set'=>array('grades.$'=>"303"));
$ismore = array("multiple" => true);
$collection->update($where,$param,$ismore);

例2

db.test2.insert(
 {
 "content" : "this is a blog post.",
 "comments" :
 [
 {
 "author" : "Mike",
 "comment" : "I think that blah blah blah...",
 },
 {
 "author" : "John",
 "comment" : "I disagree."
 }
 ]
 }
);
//查找名为Mike的记录,并且该人的名字改成tank
db.test2.update( { "comments.author": "Mike"},
 { $set: { "comments.$.author" : "tank" } }
 );

相同功能php代码:

$where = array("comments.author"=>"John");
$param = array('$set'=>array('comments.$.author'=>"tank"));
$ismore = array("multiple" => true);
$collection->update($where,$param,$ismore);

二,$addToSet 如果数组中没有该数据,向数组中添加数据,如果该数组中有相同数组,不添加

db.test3.insert(
 {"_id" :6, "grades" : [ "aaa", "bbb", "ccc" ]}
 );
db.test3.update( { _id: 6 }, { $addToSet: { grades: "ddd"  } });

相同功能php代码:

$where = array("_id"=>6);
$param = array('$addToSet'=>array('grades'=>"eee"));
$collection->update($where,$param);

三,$pop删除数组数据

db.test3.update( { _id: 6 }, { $pop: { grades: -1 } }); //从头删除 
db.test3.update( { _id: 6 }, { $pop: { grades: 1 } }); //从尾删除

相同功能php代码:

$where = array("_id"=>6);
$param = array('$pop'=>array('grades'=>-1));
$collection->update($where,$param);

四,$pull和$pullAll删除指定数据

1,$pull

> db.test3.find();
{ "_id" : 6, "grades" : [ "ccc", "ddd" ] }
{ "_id" : 7, "grades" : [ "aaa", "bbb", "ccc" ] }
{ "_id" : 8, "grades" : [ "aaa", "bbb", "ccc", "ddd", "eee" ] }
> db.test3.update(
 { grades: "aaa" },
 { $pull: { grades: "aaa" } }, //支持这种查找或匹配 $pull: { votes: { $gte: 6 } }
 { multi: true }
 );
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })

相同功能php代码:

$where = array("grades"=>"bbb");
$param = array('$pull'=>array('grades'=>"bbb"));
$ismore = array("multiple" => true);
$collection->update($where,$param,$ismore);

2,$pullAll

db.students.update( { _id: {$gt:1} },
 { $pullAll: { "grades": [90,92] } } //只支持数组
 );

相同功能php代码:

$where = array("grades"=>"ddd");
$param = array('$pullAll'=>array('grades'=>array("ddd","eee")));
$ismore = array("multiple" => true);
$collection->update($where,$param,$ismore);

五,$push,$each,$sort,$slice,$position

1,各元素解释

$push 向数组中添加元素

$each 循环数据

$sort 对数组进行排序

$slice 对整个collection表进行数据裁减,用的时候一定要当心

$position 插入数据的位置。

2,实例

db.test4.insert(
{
 "_id" : 5,
 "quizzes" : [
 { wk: 1, "score" : 10 },
 { wk: 2, "score" : 8 },
 { wk: 3, "score" : 5 },
 { wk: 4, "score" : 6 }
 ]
}
);
db.test4.update( { _id: 5 },
 { $push: { quizzes: { $each: [ { wk: 5, score: 8 },
                                { wk: 6, score: 7 },
                                { wk: 7, score: 6 } ],
                       $sort: { score: -1 },
                       $slice: 3,
                       $position:2
                      }
           }
 }
 );

相同功能php代码:

$where = array("_id"=>5);
$param = array('$push'=>array('quizzes'=>array('$each'=>array(array("wk"=>9,"score"=>10),array("wk"=>20,"score"=>11)),
                                               '$sort'=>array("score"=>-1),
                                               '$position'=>2,
                                               '$slice'=>3        //用$slice一定要小心,在这里会把整表数据裁减成3条
                                              )
                                   )
                       );
$collection->update($where,$param);
mongodb update 数组 操作 前一篇文章说到了mongodb update 的字符操作,下面说一下mongodb update的数组操作,用的版本是mongodb2.6.3。 一,$美元符号,在update中,可理解为数组下标 例1 db.students.insert( //插入测试数据 [ {"_id" :6, "grades" : [ 80, 85, 90 ],"score":[10,40,54]}, {"_id" :7, "grades" : [ 88, 90, 92 ],"score":[100,30,51]} ] ); //把满足score大于90的grades,数组的第一个元素设置成88 db.students.update( { score: {$gt:90} }, { $set: { "grades.$" : 88 } } [...]mongodb update 数组 操作
声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
MySQLにユーザーを追加:完全なチュートリアルMySQLにユーザーを追加:完全なチュートリアルMay 12, 2025 am 12:14 AM

MySQLユーザーを追加する方法を習得することは、データベース管理者と開発者にとって重要です。これは、データベースのセキュリティとアクセス制御を保証するためです。 1)CreateUserコマンドを使用して新しいユーザーを作成し、2)付与コマンドを介してアクセス許可を割り当て、3)FlushPrivilegesを使用してアクセス許可を有効にすることを確認します。

MySQL文字列データ型のマスター:Varchar vs. Text vs. CharMySQL文字列データ型のマスター:Varchar vs. Text vs. CharMay 12, 2025 am 12:12 AM

choosecharforfixed-lengthdata、varcharforvariable-lengthdata、andtextforlargetextfields.1)chariseffienceforconsistent-lengthdatalikecodes.2)varcharsuitsvariaible-lengthdatalikenames、balancingflexibilityandperformance.3)Textisidealforforforforforforforforforforforidex

MySQL:文字列データ型とインデックス:ベストプラクティスMySQL:文字列データ型とインデックス:ベストプラクティスMay 12, 2025 am 12:11 AM

MySQLの文字列データ型とインデックスを処理するためのベストプラクティスには、次のものが含まれます。1)固定長のchar、可変長さのvarchar、大規模なテキストのテキストなどの適切な文字列タイプを選択します。 2)インデックス作成に慎重になり、インデックスを避け、一般的なクエリのインデックスを作成します。 3)プレフィックスインデックスとフルテキストインデックスを使用して、長い文字列検索を最適化します。 4)インデックスを定期的に監視および最適化して、インデックスを小さく効率的に保つ。これらの方法により、読み取りと書き込みのパフォーマンスをバランスさせ、データベースの効率を改善できます。

MySQL:リモートでユーザーを追加する方法MySQL:リモートでユーザーを追加する方法May 12, 2025 am 12:10 AM

toaddauserremotelytomysql、フォローステープ:1)connecttomysqlasroot、2)createanewuserwithremoteaccess、3)grantniverayprivileges、and4)flushprivileges.

MySQL文字列データ型の究極のガイド:効率的なデータストレージMySQL文字列データ型の究極のガイド:効率的なデータストレージMay 12, 2025 am 12:05 AM

tostorestringseffiedlyinmysql、choosetherightdatatypebasedonyourneadss:1)usecharforfixed-lengthstringslikecountrycodes.2)usevarforvariable-lengthstringslikenames.3)usetextfor forlong-formtextcontent.4)useblobforborikedalikeimages

mysql blob vs.テキスト:大きなオブジェクトに適したデータ型を選択するmysql blob vs.テキスト:大きなオブジェクトに適したデータ型を選択するMay 11, 2025 am 12:13 AM

MySQLのBLOBおよびテキストデータ型を選択する場合、BLOBはバイナリデータの保存に適しており、テキストはテキストデータの保存に適しています。 1)BLOBは、写真やオーディオなどのバイナリデータに適しています。2)テキストは、記事やコメントなどのテキストデータに適しています。選択するときは、データプロパティとパフォーマンスの最適化を考慮する必要があります。

MySQL:製品にルートユーザーを使用する必要がありますか?MySQL:製品にルートユーザーを使用する必要がありますか?May 11, 2025 am 12:11 AM

いいえ、Youは、usotherootuserinmysqlforyourproduct.instead、createpificusers withlimitedprivilegestoenhancesecurityandperformance:1)createanewuserwithastrongpassword、2)grantonlynlyneversearpermissionStothisuser、3)正規環境筋肉筋周辺の環境

MySQL文字列データ型説明:データに適したタイプを選択するMySQL文字列データ型説明:データに適したタイプを選択するMay 11, 2025 am 12:10 AM

mysqlstringdatatypesshouldbechosenbadedatacharacteristicsandusecases:1)usecharforfixed-lengthstringslikecountrycodes.2)usevarforvariable-lengthstringslikenames.3)usebinaryorvarniaryforbinarydatalikecryptograpograpogrationckeys.4)使用

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

AtomエディタMac版ダウンロード

AtomエディタMac版ダウンロード

最も人気のあるオープンソースエディター

SublimeText3 英語版

SublimeText3 英語版

推奨: Win バージョン、コードプロンプトをサポート!

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

EditPlus 中国語クラック版

EditPlus 中国語クラック版

サイズが小さく、構文の強調表示、コード プロンプト機能はサポートされていません

DVWA

DVWA

Damn Vulnerable Web App (DVWA) は、非常に脆弱な PHP/MySQL Web アプリケーションです。その主な目的は、セキュリティ専門家が法的環境でスキルとツールをテストするのに役立ち、Web 開発者が Web アプリケーションを保護するプロセスをより深く理解できるようにし、教師/生徒が教室環境で Web アプリケーションを教え/学習できるようにすることです。安全。 DVWA の目標は、シンプルでわかりやすいインターフェイスを通じて、さまざまな難易度で最も一般的な Web 脆弱性のいくつかを実践することです。このソフトウェアは、