在Mongo中使用$ exists与动态键名和节点的本机驱动程序 [英] using $exists in Mongo with dynamic key names and the native driver for node

查看:89
本文介绍了在Mongo中使用$ exists与动态键名和节点的本机驱动程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这样的集合中有一个文档:

I have a document in a collection like so:

{
  container : {
    P39433: 2,
    P30213: 4
  }
}

值"P39433"和"P30213"在程序中动态生成.我可以直接对mongo使用点符号来运行以下查询,并得到所需的结果

The values 'P39433' and 'P30213' are dynamically generated in the program. I can run the following query using the dot notation against mongo directly and I get the desired result

db.collection.findOne({ "container.P00000" : { $exists : false } }) 

我拿回了文件.即,我只想获取该字段不存在的文档.

I get the document back. i.e. I only want to get the document if the field does not exist.

我的问题是,当值P00000时,如何使用本机驱动程序在Node中运行该查询 包含在变量中.

My question is how can I run that query in Node using the native driver when the value P00000 is contained in a variable.

我通常的解决方案是像下面那样构造查询,但是它不返回结果.

My usual solution is to structure the query like below but it does not return a result.

var fieldName = 'P00000';
var dynObj = {};
dynObj[fieldName] = { $exists : false };
db.collection.findOne( { "container" : dynObj }); 

推荐答案

您已经关闭.试试这个:

You're close. Try this:

var fieldName = 'P00000';
var dynObj = {};
dynObj["container." + fieldName] = { $exists: false };
db.collection.findOne(dynObj); 

更新

现在,Node.js 4+支持计算出的属性名称,您可以通过以下步骤一步创建dynObj:

Now that Node.js 4+ supports computed property names, you can create dynObj in one step as:

var dynObj = {
    ["container." + fieldName]: { $exists: false }
};

这篇关于在Mongo中使用$ exists与动态键名和节点的本机驱动程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆