2017-03-06 68 views
1

我有以下模式的集合指數,的MongoDB的Java如何插入新的對象爲首發數組對象

 { 
       "_id" : ObjectId("58b9d6b9e02fd02963b7d227"), 
       "id" : 1, 
       "ref" : [ 
         { 
           "no" : 101 
         }, 
         { 
           "no" : 100 
         } 
         ] 
     } 

當我試圖子對象推到對象的ArrayList中,它加入到結束陣列的,但我的目標是推動對象到一個數組的開始索引,我試着用這個代碼,但它插入對象到數組的結束失敗,

Java代碼,

  Document push = new Document().append("$push", new Document().append("ref", new Document().append("no", 102))); 
      collection.updateMany(new Document().append("id", 1), push); 

ExpectedResul t應該是,

  { 
        "_id" : ObjectId("58b9d6b9e02fd02963b7d227"), 
        "id" : 1, 
        "ref" : [ 
          { 
            "no" : 102 
          }, 
          { 
            "no" : 101 
          }, 
          { 
            "no" : 100 
          } 
          ] 
      } 
+0

護理闡述什麼是失敗?顯示你得到的迴應? – Coder

回答

1

使用$ position修飾符來指定數組中的位置。

的MongoDB-Java驅動程序,

ArrayList<Document> docList = new ArrayList<Document>(); 
docList.add(new Document().append("no", 102)); 
Document push = new Document().append("$push", new Document().append("ref", new Document().append("$each", docList).append("$position", 0))); 
collection.updateMany(new Document().append("id", 1), push); 
+0

謝謝,@radhakrishnan現在工作, –

+0

@Ajith高興它爲你工作,你可以接受答案。 – radhakrishnan

0

這裏是替代其使用$sort以改變陣列。

Document push = new Document().append("$push", new Document().append("ref", new Document().append("$each", Arrays.asList(new Document("no", 101))).append("$sort", -1))); 
collection.updateMany(new Document().append("id", 1), push); 
相關問題