小编Bla*_*ven的帖子

无法推断查询字段以在插入时设置错误

我正在尝试使用"findAndModify"来实现"getOrCreate"行为.我正在使用本机驱动程序在nodejs中工作.

我有:

var matches = db.collection("matches");
matches.findAndModify({
        //query
        users: {
            $all: [ userA_id, userB_id ]
        }, 
        lang: lang, 
        category_id: category_id
    }, 
    [[ "_id", "asc"]], //order
    {
        $setOnInsert: { 
            users: [userA_id, userB_id], 
            category_id: category_id, 
            lang: lang, 
            status: 0
        }
    }, 
    {
        new:true, 
        upsert:true
    }, function(err, doc){
        //Do something with doc
    });
Run Code Online (Sandbox Code Playgroud)

我想要做的是:"找到与指定用户,lang和类别的特定匹配...如果找不到,插入一个具有指定数据的新用户"

Mongo抛出这个错误:

Error getting/creating match { [MongoError: exception: cannot infer query fields to set, path 'users' is matched twice]
  name: 'MongoError',
  message: 'exception: cannot infer query fields to set, path …
Run Code Online (Sandbox Code Playgroud)

javascript mongodb mongodb-query node-mongodb-native

6
推荐指数
1
解决办法
777
查看次数

制作几个简单订阅和一个复杂订阅有什么区别?

保持几个简单(普通)订阅和保持单个复杂(多个级别)之间是否有任何实际区别?(例如发布复合)

在我看来应该没有任何区别,但我想确定.我更喜欢坚持普通的潜艇,因为它似乎使代码在高度模块化的项目中更加清晰,但前提是这不会带来任何性能或可伸缩性问题.

那么,有人可以帮助我吗?

javascript meteor

6
推荐指数
1
解决办法
63
查看次数

Mongodb计算符合条件的所有对象中的所有数组元素

我有一个集合,它是对象的活动日志,如下所示:

{
    "_id" : ObjectId("55e3fd1d7cb5ac9a458b4567"),
    "object_id" : "1",
    "activity" : [ 
        {
            "action" : "test_action",
            "time" : ISODate("2015-08-31T00:00:00.000Z")
        },
        {
            "action" : "test_action",
            "time" : ISODate("2015-08-31T00:00:22.000Z")
        }
    ]
}

{
    "_id" : ObjectId("55e3fd127cb5ac77478b4567"),
    "object_id" : "2",
    "activity" : [ 
        {
            "action" : "test_action",
            "time" : ISODate("2015-08-31T00:00:00.000Z")
        }
    ]
}

{
    "_id" : ObjectId("55e3fd0f7cb5ac9f458b4567"),
    "object_id" : "1",
    "activity" : [ 
        {
            "action" : "test_action",
            "time" : ISODate("2015-08-30T00:00:00.000Z")
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

如果我跟随查询:

db.objects.find({
    "createddate": {$gte : ISODate("2015-08-30T00:00:00.000Z")},
    "activity.action" : "test_action"}
    }).count()
Run Code Online (Sandbox Code Playgroud)

它返回包含"test_action"的文档计数(此集合中为3),但我需要计算所有test_actions(此集合中为4).我怎么做?

mongodb mongodb-query aggregation-framework

6
推荐指数
2
解决办法
9509
查看次数

Mongodb Aggregation中的多个$ group with java

这是我的查询,

db.product.aggregate([
{ $match : {categoryID : 4 } },
{ "$group" : { "_id" : { "productID": "$productID", 
                         "articleID": "$articleID", "colour":"$colour",
                         "set&size": { "sku" : "$skuID", "size" : "$size" },  
                        }, 
              }
},
{ "$group" : { "_id" : { "productID": "$_id.productID", "colour":"$_id.colour" }, 

   "size": { "$addToSet" : { "sku" : "$_id.set&size.sku", 
                                           "size" : "$_id.set&size.size" }
                         },   
 }
},
{"$project":{
     "_id":0,
     "productID":  "$_id.productID",
     "colour":"$_id.colour",
     "size":"$size",
     }
   },

   ]);
Run Code Online (Sandbox Code Playgroud)

通过在mongo shell上执行此查询,我得到了完美的输出.

产量

{
"_id": {
    "productID": "PRD1523",
    "colour": "GREEN"
}, …
Run Code Online (Sandbox Code Playgroud)

java mongodb mongodb-query aggregation-framework

6
推荐指数
1
解决办法
2795
查看次数

Mongo按计算条件排序

我有一个Mongo的消息集合,如下所示:

{
  'recipients': [],
  'unRead': [],
  'content': 'Text'
}
Run Code Online (Sandbox Code Playgroud)

收件人是一组用户ID,unRead是尚未打开邮件的所有用户的数组.这是按预期工作,但我需要查询所有消息的列表,以便它返回前20个结果,首先优先考虑未读的结果,如下所示:

db.messages.find({recipients: {$elemMatch: userID} })
  .sort({unRead: {$elemMatch: userID}})
  .limit(20)
Run Code Online (Sandbox Code Playgroud)

但这不起作用.根据结果​​是否符合某个标准,对结果进行优先排序的最佳方法是什么?

mongodb mongodb-query aggregation-framework

6
推荐指数
1
解决办法
3992
查看次数

我可以在mongoose聚合之前使用populate吗?

我有两个模型,一个是用户

 userSchema = new Schema({
     userID: String,
     age: Number
 });
Run Code Online (Sandbox Code Playgroud)

另一个是每天为所有用户记录的分数

 ScoreSchema = new Schema({
     userID: {type: String, ref: 'User'},
     score: Number,
     created_date = Date,
     ....
 })
Run Code Online (Sandbox Code Playgroud)

对于满足特定要求的用户,我想对得分进行一些查询/计算,比方说我想计算所有用户的得分平均值大于20天.

我的想法是,首先做填入的成绩来填充用户的年龄,然后做汇总之后.

就像是

Score.
    populate('userID','age').
    aggregate([
        {$match: {'userID.age': {$gt: 20}}},
        {$group: ...},
        {$group: ...}
    ], function(err, data){});
Run Code Online (Sandbox Code Playgroud)

在聚合之前使用populate是否可以?或者我首先找到满足要求的所有userID并将它们保存在一个数组中,然后使用$ in来匹配得分文档?

mongoose mongodb mongodb-query aggregation-framework

6
推荐指数
1
解决办法
6413
查看次数

MongoDB嵌套了子文档的文档验证

我得到了一个如下结构的文档.我的问题是如何在数据库端进行嵌套部分"角色"验证.我的要求是:

  • 角色大小可以是0或大于1.
  • 如果创建了角色,则为角色存在name和created_by.

    {
      "_id": "123456",
      "name": "User Name",
      "roles": [
        {
          "name": "mobiles_user",
           "last_usage_at": {
             "$date": 1457000592991
            },
            "created_by": "987654",
            "created_at": {
              "$date": 1457000592991
            }
        },
        {
          "name": "webs_user",
           "last_usage_at": {
             "$date": 1457000592991
            },
            "created_by": "987654",
            "created_at": {
              "$date": 1457000592991
            }
        },
      ]
    }
    
    Run Code Online (Sandbox Code Playgroud)

目前,我只针对那些没有嵌套的属性执行以下操作:

db.createCollection( "users",
   { "validator" : {
     "_id" : {
         "$type" : "string"
      },
      "email" : {
         "$regex" : /@gmail\.com$/
      },
      "name" : {
         "$type" : "string"
      }
   }
} )
Run Code Online (Sandbox Code Playgroud)

任何人都可以建议如何进行嵌套文档验证?

mongodb

6
推荐指数
2
解决办法
2173
查看次数

在Mongoose中对嵌套的子文档进行排序和分组

我有一个架构,Comment如下所示.这是一个"评论"和"回复"系统,但每个评论和回复都有多个版本.当用户想要查看评论时,我想只返回最新版本statusAPPROVED.

const Version = new mongoose.Schema({
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  },
  body: String,
  created: Date,
  title: String,
  status: {
    type: String,
    enum: [ 'APPROVED', 'OPEN', 'CLOSED' ]
  }
})

const Reply = new mongoose.Schema({
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  },
  created: Date,
  versions: [ Version ]
})

const Comment = new mongoose.Schema({
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  },
  created: Date,
  versions: [ Version ],
  replies: [ Reply ]
})
Run Code Online (Sandbox Code Playgroud)

我已让父母 …

javascript mongodb node.js mongodb-query aggregation-framework

6
推荐指数
1
解决办法
774
查看次数

猫鼬查询以过滤数组并填充相关内容

我试图查询该属性,该属性是对另一个架构的引用和一些其他数据的数组。为了更好的说明,以下是模式:

    var orderSchema = new Schema({
        orderDate: Date,
        articles: [{
            article: {
                type: Schema.Types.ObjectId,
                ref: 'Article'
            },
            quantity: 'Number'
        }]
    }),
    Order = mongoose.model('Order', orderSchema);
Run Code Online (Sandbox Code Playgroud)

虽然我成功地查询了引用,即:

Order.find({}).populate('articles.article', null, {
    price: {
        $lte: 500
    }
}).exec(function(err, data) {
    for (var order of data) {
        for (var article of order.articles) {
            console.log(article);
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

我在查询quantity属性时遇到了一些问题,即这不起作用:

Order.find({}).where({
    'articles.quantity': {
        $gte: 5
    }
}).populate('articles.article', null, {
    /*price: {
        $lte: 500
    }*/
}).exec(function(err, data) {
    for (var order of data) {
        for …
Run Code Online (Sandbox Code Playgroud)

mongoose mongodb node.js mongodb-query aggregation-framework

6
推荐指数
1
解决办法
2万
查看次数

计算包含字段的文档数量

我有这三个MongoDB文档:

{ 
    "_id" : ObjectId("571094afc2bcfe430ddd0815"), 
    "name" : "Barry", 
    "surname" : "Allen", 
    "address" : [
        {
            "street" : "Red", 
            "number" : NumberInt(66), 
            "city" : "Central City"
        }, 
        {
            "street" : "Yellow", 
            "number" : NumberInt(7), 
            "city" : "Gotham City"
        }
    ]
}

{ 
    "_id" : ObjectId("57109504c2bcfe430ddd0816"), 
    "name" : "Oliver", 
    "surname" : "Queen", 
    "address" : {
        "street" : "Green", 
        "number" : NumberInt(66), 
        "city" : "Star City"
    }
}
{ 
    "_id" : ObjectId("5710953ac2bcfe430ddd0817"), 
    "name" : "Tudof", 
    "surname" : "Unknown", 
    "address" : "homeless"
}
Run Code Online (Sandbox Code Playgroud)

该 …

mongodb mongodb-query aggregation-framework

6
推荐指数
1
解决办法
1万
查看次数