如何通过使用Mongoose MongoDB 2.6插入子文档中数组中的特定位置 [英] How to insert to the certain position in the array in the subdocument by using Mongoose an MongoDB 2.6

查看:274
本文介绍了如何通过使用Mongoose MongoDB 2.6插入子文档中数组中的特定位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

A great explanation of how to use new $position operator of Mongodb 2.6 by using Mongoose was given in the answer to my question. The suggested solution works perfect for simple arrays. If array is in subdocument or each element of array is array the suggested solution doesn't work. I mean something like this:

List.collection.update(
{/*....*/},
{ "$push": {
    "subdocument.list": {
      "$each": [ 1, 2, 3 ],
      "$position": 0 }
    }
},function(err,NumAffected) {
  console.log("done");

});

List.collection.update(
{/*....*/},
{ "$push": {
    "list1.$.list2": {
      "$each": [ 1, 2, 3 ],
      "$position": 0 }
    }
},function(err,NumAffected) {
  console.log("done");

});

推荐答案

不确定问题出在哪里:

db.list.insert({ "list": { "sub": [4] } })
db.list.update(
    {},
    { "$push": { "list.sub": { "$each": [1,2,3], "$position": 0 } } }
)

{ "list" : { "sub" : [ 1, 2, 3, 4 ] } }

因此可以正常工作.

对于另一个示例:

db.list.insert({
    outer: [
       {
           key: "a", 
           inner: [4]
       },
       {
           key: "b", 
           inner: [4]
       }
   ]
})

db.list.update(
    { "outer.key": "b" },
    { "$push": { 
        "outer.$.inner": { 
            "$each": [1,2,3], "$position": 0 
        }
    }}
)

再次达到预期:

{
    "outer" : [
            {
                    "key" : "a",
                    "inner" : [
                            4
                    ]
            },
            {
                    "key" : "b",
                    "inner" : [
                            1,
                            2,
                            3,
                            4
                    ]
            }
    ]
}

已经解释了与特定驱动程序的交互,因此数据中必须有一些不同之处,但是如果是这样,则这些语句无效.

The interaction with specific drivers was already explained so there must be something different in the data, but if so then those statements are not valid.

使用猫鼬也是一样:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost/nodetest');

var listSchema = new Schema({

});

var List = mongoose.model( "List", listSchema );
var Other = mongoose.model( "Other", listSchema );

  List.collection.update(
    {},
    { "$push": {
    "list.sub": {
      "$each": [ 1, 2, 3 ],
      "$position": 0 }
    }
    },function(err,NumAffected) {
      console.log("done");

    }
  );


  Other.collection.update(
    { "outer.key": "b" },
    { "$push": {
        "outer.$.inner": {
            "$each": [ 1, 2, 3 ],
            "$position": 0
        }
    }},function(err,NumAffected) {
      console.log("done2")
    }
  );

这篇关于如何通过使用Mongoose MongoDB 2.6插入子文档中数组中的特定位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆