【问题标题】:How to push subdocument into an array using MongoDB如何使用 MongoDB 将子文档推送到数组中
【发布时间】:2011-10-14 07:21:58
【问题描述】:

我正在使用 Codeigniter 和 MongoDB 开发一个 API。 在用户文档中,我得到了一个名为 following 的项目,它是一个数组。 我需要将包含用户全名和 ID 的子文档推送到此数组中。

每次我尝试子文档最终都是一个子数组。

我正在使用 Alex Bilbie 的 MongoDB 库,这是我的查询:

$this->mongo_db->where(array('_id'=>$user_id))->push('following', array("{id: 'aa', fullname: 'James Bond'}"))->update('users');

我需要这样的结果:

following : [
    { fullname : "James", id : aa},
    { fullname : "Jane", id : bb}
  ]

更新:

我是这样解决的:

$this->mongo_db->where(array('_id'=>$user_id))->push('following', array('fullname'=>'Earl Spencer','id'=>'bb'))->update('users');

【问题讨论】:

    标签: codeigniter mongodb


    【解决方案1】:
      String fullname = "James";
      String id = "aa"
      var myResult = this.mongo_collections_Users.FindAndModify(
    
      Query.And(Query.EQ("_id", new ObjectId(id_as_string))),
      SortBy.Ascending("_id"),
      Update.PushWrapped<item_following>("following", new item_following(fullname, id) )),
      true
      );
    

    此代码将在具有特定_id 的“用户”集合中找到文档。 之后将“推”(添加)一个新项目到“以下”数组中。

    如果您想存储对用户的引用,而不是新的“item_following”,请 使用“MongoDbRef”。

    希望能帮到你

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-11
      • 1970-01-01
      • 2017-03-26
      • 2014-12-20
      • 1970-01-01
      • 2014-07-29
      相关资源
      最近更新 更多