简体   繁体   English

你如何在同一个Mongoose.js查询中使用$和$或$?

[英]How do you utilize $and, $or, $exists in the same Mongoose.js query?

I need to query documents for an account that either has no expiration[expires] (does not exist) or the expiration date is after 2/2/14. 我需要查询没有到期[到期](不存在)或到期日期在2/2/14之后的帐户的文档。 To do so, my mongodb query is: 为此,我的mongodb查询是:

db.events.find({ _account: ObjectId("XXXX"), 
    $or: [
        {expires: {$gt: ISODate('2014-02-02')}}, 
        {expires: {$exists: false}}
    ]
});

I'm having trouble with the correct mongoose .or() .and() .exists() chaining, how would I convert this into Mongoose? 我遇到了正确的猫鼬.or() .and() .exists()链接有问题,如何将其转换为Mongoose?

Thanks! 谢谢!

There should be nothing wrong with using the same syntax, more or less as in the shell. 使用相同的语法应该没有任何问题,或多或少与shell一样。 It's still javascript, just without the shell helpers. 它仍然是javascript,只是没有shell助手。

Events.find({ _account: "XXXX", 
  $or: [
    {expires: {$gt: Date(2014,02,02)}},
    {expires: {$exists: false }}
}, function(err, events) {
    if (err) // TODO
    // do something with events
});

Alternately you are using other helpers to build the query: 或者,您正在使用其他帮助程序来构建查询:

var query = Events.find({ _account: "XXXX" });

query.or(
    {expires: {$gt: Date(2014,02,02)}},
    {expires: {$exists: false }}
);

query.exec(function(err, events) { 
   if (err) // TODO
   // do something with events
});

Or other combinations. 或其他组合。 These 'helpers' largely exist in drivers for syntax parity with other non-dynamic languages like Java. 这些“助手”主要存在于与其他非动态语言(如Java)进行语法奇偶校验的驱动程序中。 You can look for examples of QueryBuilder usage in Java if you prefer this way and can't find the node references. 如果您喜欢这种方式并且无法找到节点引用,则可以在Java中查找QueryBuilder使用示例。 For mongoose there is the documentation for queries that is worth a look. 对于mongoose,有一些值得一看的查询文档

Dynamic languages have a more native approach to defining such object structures as used for queries etc. So most people prefer to use them. 动态语言有一种更原生的方法来定义用于查询等的对象结构。因此大多数人更喜欢使用它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM