MongoDB使用LIKE条件在multipe文档上创建$ lookup

时间:2017-07-18 09:47:32

标签: mongodb nosql

假设我有2个文件,我想加入。

客户文件

/* 1 */
{
    "_id" : ObjectId("596d5aacb02f922a92475698"),
    "code" : "A001",
    "name" : "NameA001",
    "age" : 35
}

/* 2 */
{
    "_id" : ObjectId("596d5aacb02f922a9247569a"),
    "code" : "A002",
    "name" : "NameA002",
    "age" : 52
}

/* 3 */
{
    "_id" : ObjectId("596d5aacb02f922a9247569c"),
    "code" : "A003",
    "name" : "NameA003",
    "age" : 47
}

促销文件

/* 1 */
{
    "_id" : ObjectId("596d5ad3b02f922a924756c3"),
    "ucode" : "SL-A001",
    "pname" : "Product 1",
    "quantity" : 3
}

/* 2 */
{
    "_id" : ObjectId("596d5ad3b02f922a924756c5"),
    "ucode" : "SL-A001",
    "pname" : "Product 2",
    "quantity" : 5
}

/* 3 */
{
    "_id" : ObjectId("596d5ad3b02f922a924756cd"),
    "ucode" : "SL-A002",
    "pname" : "Product 3",
    "quantity" : 10
}

/* 4 */
{
    "_id" : ObjectId("596d5ad3b02f922a924756d1"),
    "ucode" : "SL-A003",
    "pname" : "Product 8",
    "quantity" : 5
}

我想加入客户和销售文件,以获得年龄小于50岁的所有客户。结果看起来像

/* 1 */
{
    "_id" : ObjectId("596d5aacb02f922a92475698"),
    "code" : "A001",
    "name" : "NameA001",
    "age" : 35,
    "history" : [ 
        {
            "_id" : ObjectId("596d5ad3b02f922a924756c3"),
            "ucode" : "SL-A001",
            "pname" : "Product 1",
            "quantity" : 3
        }, 
        {
            "_id" : ObjectId("596d5ad3b02f922a924756c5"),
            "ucode" : "SL-A001",
            "pname" : "Product 2",
            "quantity" : 5
        }
    ]
}

/* 2 */
{
    "_id" : ObjectId("596d5aacb02f922a9247569c"),
    "code" : "A003",
    "name" : "NameA003",
    "age" : 47,
    "history" : [ 
        {
            "_id" : ObjectId("596d5ad3b02f922a924756d1"),
            "ucode" : "SL-A003",
            "pname" : "Product 8",
            "quantity" : 5
        }
    ]
}

我写了汇总语句,但我不知道如何在$ lookup上制作LIKE条件。

db.customer.aggregate([
   {
      $match: { "age": { $lt: 50 } }
   },
   {
      $lookup:
         {
            from: "sale",
            localField: "code",
            foreignField: "ucode",
            as: "history"
        }
   }
])

如何在localField或foreignField上使用Like条件编写查找? (或任何加入类似条件的建议) 提前谢谢。

0 个答案:

没有答案