假设我的集合中有以下文档
{'name':'toothpaste','price':'{"currency":"USD","value":17}'}
{'name':'laptop','price':'{"currency":"EUR","value":1080}'}我想一次查询单据,单据的价格币种是USD,价格值小于100。请记住,价格列n包含一个JSON字符串,而不是嵌入式对象
发布于 2021-06-28 00:49:01
要在查询中使用自定义函数,请查看$function operator of the aggregation framework。这是Mongo >= 4.4的一个新特性(感谢@Victor)
至于您的查询,您可以这样做:
db.items.find({"$expr": { "$function": {
body: function(price) {
const parsed = JSON.parse(price);
return parsed.currency === "USD" && parsed.value <= 100
},
args: ["$price"],
lang: "js"
} }})我发现的一件事是,为了让JSON.parse()正确工作,必须用双引号保存JSON字符串(您这样做是正确的
使用mongo Web shell here测试代码
>>> db.items.insertMany([ { "name": "toothpaste", "price": '{"currency":"USD","value":17}' }, { "name": "laptop", "price": '{"currency":"EUR","value":1080}' } ])
>>> db.items.find({"$expr": { "$function": {
body: function(price) {
const parsed = JSON.parse(price);
return parsed.value === 17
},
args: ["$price"],
lang: "js"
} }})https://stackoverflow.com/questions/68153068
复制相似问题