Mongodb /meteor收集检查子文档字段是否存在,当字段是一个变量

mongodb/meteor collection check if subdocument field exists when field is a variable

本文关键字:字段 变量 一个 是否 meteor 检查 Mongodb 文档 存在      更新时间:2023-09-26

我正在尝试使用以下内容

collection.find({"myField."+variable : {$exists: true})

但显然这不起作用,因为集合不接受字符串。相反,我尝试在JSON中构建一个完整的查询字符串,但这无法正确解析,因为我只是搜索字段名,而不是整个对象

var qry = '{"myField.'+variable+'"}'; //no go

我也尝试过流星集合字段逻辑

var qry = 'myField.'+variable; 
collection.find({}, {fields: {qry: 1}})

无效。我知道查询可以接受JSON对象,但我不确定如何写这个

试一试:

var selector = {};
selector["myField." + variable] = {$exists: true};
Collection.find(selector);

这可以使用括号符号

来完成
var fieldQuery = {};
fieldQuery["myField"+variable] = {$exists: true};

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors Bracket_notation