我在MongoDB
中有以下对象:
[
{
"name": "pencil",
"purchase_record": {
"1":"$900",
"2":"$1000",
"3":"$1100",
"4":"$1200"
}
},
{
"name": "pen",
"purchase_record": {
"1":"$1000",
"2":"$1200",
"3":"$900",
"4":"$1100",
"5":"$1100"
}
}
]
是否有一种方法可以获取每条记录的purchase_record
长度?
您应该考虑更改文档结构,使purchase_record
成为@JohnnyHK指出的数组。最好的方法是使用"bulk"操作。
var bulk = db.xx.initializeUnorderedBulkOp();
var count = 0;
db.xx.find().forEach(function(doc) {
var purchase_record = doc.purchase_record;
var newRecord = [];
for(var key in purchase_record) {
if(Object.prototype.hasOwnProperty.call(purchase_record, key))
newRecord.push({'units': key, 'price': purchase_record[key]});
}
bulk.find( { '_id': doc._id } ).updateOne( {
'$set': { 'purchase_record': newRecord } } );
count++;
if(count % 300 === 0) {
// Execute per 300 operations
bulk.execute();
bulk = db.xx.initializeUnorderedBulkOp();
}
})
// Clean up queues
if (count > 0) bulk.execute();
此操作后,您的文档如下所示:
{
"_id" : ObjectId("565aad654036f6520c25a9bb"),
"name" : "pencil",
"purchase_record" : [
{
"units" : "1",
"price" : "$900"
},
{
"units" : "2",
"price" : "$1000"
},
{
"units" : "3",
"price" : "$1100"
},
{
"units" : "4",
"price" : "$1200"
}
]
}
{
"_id" : ObjectId("565aad654036f6520c25a9bc"),
"name" : "pen",
"purchase_record" : [
{
"units" : "1",
"price" : "$1000"
},
{
"units" : "2",
"price" : "$1200"
},
{
"units" : "3",
"price" : "$900"
},
{
"units" : "4",
"price" : "$1100"
},
{
"units" : "5",
"price" : "$1100"
}
]
}
您现在可以使用.aggregate()
方法,该方法提供对到.aggregate()
您的文档的聚合管道的访问,并返回“ purchase_record” $project
$project
哪个返回:
$size
您始终可以使用$size
将'purchase_record'字段添加到结果中:
对于您当前的文档结构,您可以使用db.xx.aggregate([
{ '$project': {
'_id': 0,
'name': 1,
'size_purchase_record': { '$size': '$purchase_record' }
}}
])
方法执行此操作:
{ "name" : "pencil", "size_purchase_record" : 4 } { "name" : "pen", "size_purchase_record" : 5 }
哪个返回:
'purchase_record': 1
或者
mapReduce
方法效率不高,因为它是客户端方法。
mapReduce
哪个产量:
var map = function() {
var records = [];
for(var key in this.purchase_record) {
if(Object.prototype.hasOwnProperty.call(this.purchase_record, key))
records.push(key);
}
var recordsLen = records.length;
emit(this.name, recordsLen);
};
var reduce = function(key, values) { return values; };
db.xx.mapReduce(map, reduce, { out: { inline: 1 } } );
这是一个老问题,但是对于{
"results" : [
{
"_id" : "pen",
"value" : 5
},
{
"_id" : "pencil",
"value" : 4
}
],
"timeMillis" : 1,
"counts" : {
"input" : 2,
"emit" : 2,
"reduce" : 0,
"output" : 2
},
"ok" : 1
}
,答案很容易,可从MongoDB版本3.4.4获得]]
您可以做;