我在mongodb的查询中需要一些指导。我有一个项目集合,其中包含一个包含多个字段的数组,但我只关心一个字段,即条形码字段。我需要消除条形码字符串的长度。
Items.find({this.array['barcode'].length > 6})
如果上述查询成为可能会很棒,但我相信它不是。我只需要一个条形码列表。我该如何解决这个问题? mongodb有什么可以比较字符串的长度吗?或者我是否必须使用mapReduce查询?如果我这样做,我可以对此有一些指导吗?我不确定如何写它。
谢谢
答案 0 :(得分:0)
尝试使用正则表达式。
/^\w{6}/
这表示匹配字符串开头有6个单词字符的单词。
示例:
设置:
user test;
var createProduct = function(name, barcode){
return {
name : name,
detail: {
barcode : barcode
}
};
};
db.products.drop();
for(var i = 0; i < 10; i++){
db.products.insert( createProduct( "product" + i, "1234567890".substring(0,i+1) ));
}
文件结构:
{
"_id" : ObjectId("540d3ba1242ff352caa6154b"),
"name" : "product0",
"detail" : {
"barcode" : "1"
}
}
查询:
db.products.find({ "detail.barcode" : /^\w{6}/ })
输出:
{ "_id" : ObjectId("540d3ba1242ff352caa61550"), "name" : "product5", "detail" : { "barcode" : "123456" } }
{ "_id" : ObjectId("540d3ba1242ff352caa61551"), "name" : "product6", "detail" : { "barcode" : "1234567" } }
{ "_id" : ObjectId("540d3ba1242ff352caa61552"), "name" : "product7", "detail" : { "barcode" : "12345678" } }
{ "_id" : ObjectId("540d3ba1242ff352caa61553"), "name" : "product8", "detail" : { "barcode" : "123456789" } }
{ "_id" : ObjectId("540d3ba1242ff352caa61554"), "name" : "product9", "detail" : { "barcode" : "1234567890" } }
但是,如果barcode
是数组内对象中的键,则只需要匹配的条形码值。然后你应该使用聚合函数来提取值。
设定:
user test;
var createProduct = function(name){
var o = {
name : name,
subProducts: []
};
for(var i = 0; i < 10; i++){
o.subProducts.push({
barcode : "1234567890".substring(0,i+1)
});
}
return o;
};
db.products.drop();
db.products.insert( createProduct( "newBrand") );
文件结构:
{
"_id" : ObjectId("540d4125242ff352caa61555"),
"name" : "newBrand",
"subProducts" : [
{
"barcode" : "1"
},
...
{
"barcode" : "123456789"
},
{
"barcode" : "1234567890"
}
]
}
汇总查询:
db.products.aggregate([
{ $unwind : "$subProducts" },
{ $match : { "subProducts.barcode" : /^\w{6}/ } }
]);
输出:
{ "_id" : ObjectId("540d4125242ff352caa61555"), "name" : "newBrand", "subProducts" : { "barcode" : "123456" } }
{ "_id" : ObjectId("540d4125242ff352caa61555"), "name" : "newBrand", "subProducts" : { "barcode" : "1234567" } }
{ "_id" : ObjectId("540d4125242ff352caa61555"), "name" : "newBrand", "subProducts" : { "barcode" : "12345678" } }
{ "_id" : ObjectId("540d4125242ff352caa61555"), "name" : "newBrand", "subProducts" : { "barcode" : "123456789" } }
{ "_id" : ObjectId("540d4125242ff352caa61555"), "name" : "newBrand", "subProducts" : { "barcode" : "1234567890" } }
更多信息: