我有一个字符串格式的mongo查询。如何在mongo上运行此字符串查询?
我可以在mongo shell上运行它:
db.getCollection('myCollenction').find({})
如何在node.js mongo本机驱动程序上运行相同的命令?
var query = "db.getCollection('myCollenction').find({})";
db.runCommand(query);
我有一个mongodb查询生成器,现在我需要获取生成的查询并在mongo上执行。
我正在使用node.js 8.11.1和mongodb本机节点驱动程序3.1
修改
我发现我可以运行mongodb eval 功能来做到这一点,但已弃用。还有另一种方法吗?还是有另一种方法可以在jquery-querybuilder上获取生成的条件并在我的mongo数据库上执行以获取结果?
答案 0 :(得分:0)
使用jQuery QueryBuilder附带的mongodb-support插件,您可以使用getMongo()
方法获取可以直接传递给db.collection.find()
的对象:
var rules_basic = {
condition: 'AND',
rules: [{
id: 'price',
operator: 'less',
value: 10.25
}, {
condition: 'OR',
rules: [{
id: 'category',
operator: 'equal',
value: 2
}, {
id: 'category',
operator: 'equal',
value: 1
}]
}]
};
$('#builder-basic').queryBuilder({
plugins: ['bt-tooltip-errors'],
filters: [{
id: 'name',
label: 'Name',
type: 'string'
}, {
id: 'category',
label: 'Category',
type: 'integer',
input: 'select',
values: {
1: 'Books',
2: 'Movies',
3: 'Music',
4: 'Tools',
5: 'Goodies',
6: 'Clothes'
},
operators: ['equal', 'not_equal', 'in', 'not_in', 'is_null', 'is_not_null']
}, {
id: 'in_stock',
label: 'In stock',
type: 'integer',
input: 'radio',
values: {
1: 'Yes',
0: 'No'
},
operators: ['equal']
}, {
id: 'price',
label: 'Price',
type: 'double',
validation: {
min: 0,
step: 0.01
}
}, {
id: 'id',
label: 'Identifier',
type: 'string',
placeholder: '____-____-____',
operators: ['equal', 'not_equal'],
validation: {
format: /^.{4}-.{4}-.{4}$/
}
}],
rules: rules_basic
});
$('.parse-json').on('click', function() {
var result = $('#builder-basic').queryBuilder('getMongo');
alert(JSON.stringify(result, null, 2));
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-PmY9l28YgO4JwMKbTvgaS7XNZJ30MK9FAZjjzXtlqyZCqBY6X6bXIkM++IkyinN+" crossorigin="anonymous">
<link href="https://cdn.jsdelivr.net/npm/jQuery-QueryBuilder@2.5.2/dist/css/query-builder.default.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js" integrity="sha384-vhJnz1OVIdLktyixHY4Uk3OHEwdQqPppqYR8+5mjsauETgLOcEynD9oPHhhz18Nw" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/jQuery-QueryBuilder@2.5.2/dist/js/query-builder.standalone.min.js"></script>
<div class="container">
<div class="col-md-12">
<div id="builder-basic"></div>
<div class="btn-group">
<button class="btn btn-primary parse-json" data-target="basic">Get Query</button>
</div>
</div>
</div>