首页 \ 问答 \ 基于多个子文档的MongoDB / Mongoose查询(MongoDB/Mongoose query based on multiple subdocuments)

基于多个子文档的MongoDB / Mongoose查询(MongoDB/Mongoose query based on multiple subdocuments)

我是MongoDB和Mongoose的新手。 我目前正在构建一个具有客户端集合的应用程序,该集合包含客户端拥有的一系列帐户。

我想根据客户端帐户的具体情况查询集合。 例如,我需要返回以下客户端:

  • clientType:“标准”
  • 有两个帐户:
    • accountType:“FML”,余额:$ gt 3000
    • accountType:“OMG”,余额:$ lt 3000

以下是示例文档:

{
    clientDetails: {
        cardNumber: "0123456",
        firstName: "Bob",
        lastName: "Dole",
        clientType: "Standard"
    },
    accounts: [
        {
            accountNumber: "123",
            accountType: "FML",
            balance: 4000.00
        },
        {
            accountNumber: "234",
            accountType: "OMG",
            balance: 2000
        }
    ]
}

到目前为止,我只是想出了如何构建一个查询,可以使用accountTypes [“FML”,“OMG]获取clientType”Standard“的客户端,但我无法弄清楚如何为特定的指定平衡条件accountTypes。

ClientModel
    .find({
        "clientDetails.clientType": "Standard",
        "accounts.accountType": { $all ["FML", "OMG"]
    })
    .then(
        function(){ //etc..},
        function(err){ //etc...}
    );

I'm brand new to MongoDB and Mongoose. I'm currently building an app that has a client collection that contains an array of accounts that the client has.

I'd like to query the collection based on specifics of the accounts the client has. For example, I need to return the client that is:

  • clientType: "Standard"
  • Has two accounts:
    • accountType: "FML", balance: $gt 3000
    • accountType: "OMG", balance: $lt 3000

Below is a sample document:

{
    clientDetails: {
        cardNumber: "0123456",
        firstName: "Bob",
        lastName: "Dole",
        clientType: "Standard"
    },
    accounts: [
        {
            accountNumber: "123",
            accountType: "FML",
            balance: 4000.00
        },
        {
            accountNumber: "234",
            accountType: "OMG",
            balance: 2000
        }
    ]
}

So far, I've only figured out how to build a query that can get a client of clientType "Standard" with accountTypes ["FML","OMG] but I can't figure out how to specify the balance condition for the specific accountTypes.

ClientModel
    .find({
        "clientDetails.clientType": "Standard",
        "accounts.accountType": { $all ["FML", "OMG"]
    })
    .then(
        function(){ //etc..},
        function(err){ //etc...}
    );

原文:https://stackoverflow.com/questions/43766481
更新时间:2024-01-16 15:01

最满意答案

我之前已在这篇文章中回答了这个问题。 基本上来自hasOne和hasMany的声明它们在目标模型上创建FK。 如果你认为FK在1:1的关系上停留在原始模型上,你必须使用belongsTo,甚至sequelize docs建议在这里

尽管它被称为HasOne关联,但对于大多数1:1关系,您通常需要BelongsTo关联,因为BelongsTo会在hasOne将添加到目标上的源上添加foreignKey。

对于1:N之间的关系,除了hasMany之外没有其他选项,正如我所说,它在目标模型上创建了FK,因为它是如何工作的1:N关系。


I already answered this question before on this post. Basically the declarations from hasOne and hasMany they create the FK on the destination model. If you one that FK stays on the origin model on a relation 1:1, you have to use belongsTo, even sequelize docs recommend that here.

Even though it is called a HasOne association, for most 1:1 relations you usually want the BelongsTo association since BelongsTo will add the foreignKey on the source where hasOne will add on the target.

And for a relation between 1:N you have no other option than hasMany, and as I said, it create the FK on the destination model, because thats how it works a 1:N relation.

相关问答

更多
  • 对于你的版本“sequelize”:“^ 4.13.2” : classMethods和instanceMethods被删除。 以前: const Model = sequelize.define('Model', { ... }, { classMethods: { associate: function (model) {...} }, instanceMethods: { someMethod: function () { ...} ...
  • 阅读手册https://book.cakephp.org/3.0/en/orm/associations.html 。 仔细阅读整页。 className :与当前模型关联的表的类名。 如果您要定义“User hasOne Address”关系,则className键应该等于“Addresses”。 条件 :find()兼容条件的数组,例如['Addresses.primary'=> true] 定义关联所需的类名称和条件。 $this->hasOne('Foo', [ 'class ...
  • 您需要在create方法中包含关联才能添加它。 Route .create({ name: 'route1', customers: [{ name: "customer1" }, { name: "customer2" }] }, { include: [ Customer ] }); 这将创建表中的客户。 如果要添加与两个现有客户关联的路由,则需要采用不同的方法。 Route.create( { name: "route1" } ) .th ...
  • 我之前已在这篇文章中回答了这个问题。 基本上来自hasOne和hasMany的声明它们在目标模型上创建FK。 如果你认为FK在1:1的关系上停留在原始模型上,你必须使用belongsTo,甚至sequelize docs建议在这里 。 尽管它被称为HasOne关联,但对于大多数1:1关系,您通常需要BelongsTo关联,因为BelongsTo会在hasOne将添加到目标上的源上添加foreignKey。 对于1:N之间的关系,除了hasMany之外没有其他选项,正如我所说,它在目标模型上创建了FK,因为它 ...
  • 我已经能够从IRC的mickhansen那里得到答案。 mickhansen:“你需要你所查询的那一方的关系,因为你是从汽车方面创造的,你需要汽车 - >细节关系。” 有道理。 这里有一个例子: http : //docs.sequelizejs.com/en/latest/docs/associations/#foreign-keys_1 希望这可以帮助。 I've been able to have an answer from mickhansen on IRC about this. mickhan ...
  • 考虑到Brian的帖子的评论,你的问题有点不清楚,但如果你绝对需要用户共享一组给定的位置,那么你最好使用User belongsTo location 。 这将在User创建一个locationId字段,并且您将能够GET api\Users\{userId}\location 最终,您可以设置一个location hasMany User从给定位置检索其中的所有用户 Your problem is a bit unclear, given the comments of Brian's post, but ...
  • 关系类型hasOne使用LEFT JOIN ,因此不能支持LIMIT作为选项,因为它会影响整个查询(不仅限制Day而且限制Training )。 有几种方法可以解决您的问题。 最简单的方法是将关联定义为hasMany ,但设置'limit'=>1 。 public $hasMany = array( 'FirstDay' => array( 'className' => 'Day', 'foreignKey' => 'training_id', 'fi ...
  • 两个具有hasOne关系的模型: class Model_User extends Model_Table { public $table = 'user'; function init() { parent::init(); $this->addField('name'); $this->addField('email'); $this->hasOne('role'); // field role_id in data ...
  • 目前还没有直接的方式来续集你所要求的 参考https://github.com/sequelize/sequelize/issues/3845 但你可以做到 Group.belongsTo(GroupUser) User.belongsTo(GroupUser) GroupUser.hasOne(Group) GroupUser.hasOne(User) 和嵌套包含(但这不是很有效) User.findAll({include : [{model:GroupUser, include :[{model : ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)