簡體   English   中英

MongoDb只更新數組中的一個值

[英]MongoDb Update only one value from array

我有一個mongodb的集合,看起來像這樣。

"_id" : ObjectId("554c5397ccfff21e103c9869"),
"name" : "test",
"color" : [
    "552ced22ccfff2d8183c986a_Jellow",
    "551fdd24ccfff2362e3c9869_test"
],
"updated_at" : ISODate("2015-05-08T06:11:35.303Z"),
"created_at" : ISODate("2015-05-08T06:11:35.303Z")

我想只更新數組顏色中的一個值但是當我嘗試更新數組時,它會從顏色數組中刪除所有值,並用新值替換它。 這是代碼。 我正在使用JARENGER MONGODB PACKAGE for LARAVEL

$query->where($field,'regexp','/^('.$id.')_.*/')->update([$field=>$id.'_'.$name]);

我該怎么辦呢?

您要做的是,將模式更改為{key:value}對,然后按照本教程 ,這將幫助您解決問題。 或者您可以從顏色數組中獲取所有值並替換為新值,然后更新您的文檔(我不會這樣做因為它是一種骯臟的方法!)。

編輯

嘿巴德! 我在jenssenger docs上創建了這個:


將項添加到數組。

DB::collection('users')->where('name', 'John')->push('items', 'boots');
DB::collection('users')->where('name', 'John')->push('messages', array('from' => 'Jane Doe', 'message' => 'Hi John'));

如果您不想要重復項,請將第三個參數設置為true:

DB::collection('users')->where('name', 'John')->push('items', 'boots', true);

從數組中刪除項目。

DB::collection('users')->where('name', 'John')->pull('items', 'boots');
DB::collection('users')->where('name', 'John')->pull('messages', array('from' => 'Jane Doe', 'message' => 'Hi John'));

您需要使用$set運算符。 不確定它是如何在Jessenger Mongodb中完成的,但它可能是這樣的:

$query->where($field,'regexp','/^('.$id.')_.*/')
      ->update(['$set' => [ $field=>$id.'_'.$name]]);

為什么不改變這樣的數據:

"_id" : ObjectId("554c5397ccfff21e103c9869"),
"name" : "test",
"color" : [
    { "id":"552ced22ccfff2d8183c986a", "name":"Jellow"},
    { "id":"551fdd24ccfff2362e3c9869", "name":"test"}
],
"updated_at" : ISODate("2015-05-08T06:11:35.303Z"),
"created_at" : ISODate("2015-05-08T06:11:35.303Z")

然后你可以通過id更新元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM