arrays - Mongoose 查询 : Find an element inside an array

标签 arrays node.js mongodb mongoose

这里是Mongoose/Mongo noob:

我的数据

这是我的简化数据,每个用户都有自己的文档

{ "__v" : 1,
  "_id" : ObjectId( "53440e94c02b3cae81eb0065" ),
  "email" : "test@test.com",
  "firstName" : "testFirstName",
  "inventories" : [ 
    { "_id" : "active",
      "tags" : [ 
        "inventory", 
        "active", 
        "vehicles" ],
      "title" : "activeInventory",
      "vehicles" : [ 
        { "_id" : ObjectId( "53440e94c02b3cae81eb0069" ),
          "tags" : [ 
            "vehicle" ],
          "details" : [ 
            { "_id" : ObjectId( "53440e94c02b3cae81eb0066" ),
              "year" : 2007,
              "transmission" : "Manual",
              "price" : 1000,
              "model" : "Firecar",
              "mileageReading" : 50000,
              "make" : "Bentley",
              "interiorColor" : "blue",
              "history" : "CarProof",
              "exteriorColor" : "blue",
              "driveTrain" : "SWD",
              "description" : "test vehicle",
              "cylinders" : 4,
              "mileageType" : "kms" } ] } ] }, 
    { "title" : "soldInventory",
      "_id" : "sold",
      "vehicles" : [],
      "tags" : [ 
        "inventory", 
        "sold", 
        "vehicles" ] }, 
    { "title" : "deletedInventory",
      "_id" : "deleted",
      "vehicles" : [],
      "tags" : [ 
        "inventory", 
        "sold", 
        "vehicles" ] } ] }

如您所见,每个用户都有一个 inventories 属性,该属性是一个包含 3 个库存(activeInventory、soldInventory 和 deletedInventory)的数组

我的查询

给定用户的电子邮件和车辆 ID,我希望我的查询通过查找用户的 activeInventory 并仅返回与 ID 匹配的车辆。这是我目前所拥有的:

user = api.mongodb.userModel;
ObjectId = require('mongoose').Types.ObjectId;
return user
    .findOne({email : params.username})
    .select('inventories')
    .find({'title': 'activeInventory'})
    //also tried
    //.where('title')
    //.equals('activeInventory')
    .exec(function(err, result){
        console.log(err);
        console.log(result);
    });

这样,结果就会作为一个空数组出现。我也试过 .find('inventories.title': 'activeInventory') 奇怪地返回整个库存数组。如果可能的话,我想保留链接查询格式,因为我发现它更具可读性。

我的理想查询

return user
    .findOne({email : params.username})
    .select('inventories')
    .where('title')
    .equals('activeInventory')
    .select('vehicles')
    .id(vehicleID)
    .exec(cb)

显然它不起作用,但它可以让你知道我想要做什么。

最佳答案

使用 $位置运算符,可以得到结果。但是,如果 vehicles 数组中有多个元素,所有这些元素都将在结果中返回,因为您只能在投影中使用一个位置运算符,并且您正在使用 2 个数组(一个在另一个)。

我建议你看看 aggregation framework ,因为您将获得更多的灵 active 。这是在 shell 中运行的针对您的问题的示例查询。我对 Mongoose 不熟悉,但我想这仍然会帮助你,你可以翻译它:

db.collection.aggregate([
    // Get only the documents where "email" equals "test@test.com" -- REPLACE with params.username
    {"$match" : {email : "test@test.com"}}, 
    // Unwind the "inventories" array
    {"$unwind" : "$inventories"}, 
    // Get only elements where "inventories.title" equals "activeInventory"
    {"$match" : {"inventories.title":"activeInventory"}}, 
    // Unwind the "vehicles" array
    {"$unwind" : "$inventories.vehicles"}, 
    // Filter by vehicle ID -- REPLACE with vehicleID 
    {"$match" : {"inventories.vehicles._id":ObjectId("53440e94c02b3cae81eb0069")}}, 
    // Tidy up the output
    {"$project" : {_id:0, vehicle:"$inventories.vehicles"}}
])

这是您将得到的输出:

{
        "result" : [
                {
                        "vehicle" : {
                                "_id" : ObjectId("53440e94c02b3cae81eb0069"),
                                "tags" : [
                                        "vehicle"
                                ],
                                "details" : [
                                        {
                                                "_id" : ObjectId("53440e94c02b3cae81eb0066"),
                                                "year" : 2007,
                                                "transmission" : "Manual",
                                                "price" : 1000,
                                                "model" : "Firecar",
                                                "mileageReading" : 50000,
                                                "make" : "Bentley",
                                                "interiorColor" : "blue",
                                                "history" : "CarProof",
                                                "exteriorColor" : "blue",
                                                "driveTrain" : "SWD",
                                                "description" : "test vehicle",
                                                "cylinders" : 4,
                                                "mileageType" : "kms"
                                        }
                                ]
                        }
                }
        ],
        "ok" : 1
}

关于arrays - Mongoose 查询 : Find an element inside an array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22941554/

相关文章:

javascript - 如何在JavaScript中从多维数组中获取数据?

用于二维文本数组上的类似矩阵转换的 JavaScript 库?

javascript - 无法从 JavaScript 客户端通过 https 连接到 websocket 服务器

javascript - 将 invRegex.py 移植到 Javascript (Node.js)

html - 使用 Jade 呈现的 HTML 值中的额外空格

java - mongoDB:游标 notimeout 设置在 java 客户端中不起作用

java - 从 Java 驱动程序读取时 Mongodb 随机超时 - 无法调用某些内容

java - 如何创建对类的引用数组,并在数组中存储其他几个对象的引用值?

javascript - 如何在 JS 中格式化对象数组的数组

mongodb - Golang BSON 转换