在mongodb中搜索多个条件

时间:2018-06-08 12:45:03

标签: node.js mongodb mongoose mongodb-query

我想从状态,金额,created_date,_id,货币以及Users集合中的firstName字段等字段中找到与input search string匹配的任何文档,同时我需要填充senderId和{{ 1}来自匹配的文件。

这是我的示例文档

receiverId

我正在寻找一种有效的方法来实现单mongodb查询。请帮忙:)

1 个答案:

答案 0 :(得分:1)

您可以尝试以下聚合

您可以使用$match使用$or在任何条件下搜索字符串...然后您需要$lookup填写所需收藏中的字段...并且如果您想要发件人和收件人作为对象,然后在管道的末尾使用$unwind阶段......对于created_date,您可以使用$lte $gte ... < / p>

首先,您需要检查字符串是否有效objectId

var mongodb = require("mongodb"),
objectid = mongodb.BSONPure.ObjectID;
const myMatch = []

const myArray = [
  { "status": { "$regex": "your_string" }},
  { "amount": { "$regex": "your_string" }},
  { "created_date": : "your_string" },
  { "currency": { "$regex": "your_string" }},
  { "firstName": { "$regex": "your_string" }}
]

if (objectid.isValid("your_string")) {
    myArray.push({ "_id": : mongoose.Types.ObjectId("your_string") })
}

如果你有 mongodb版本3.6

db.collection.aggregate([
  { "$match": { "$or": myArray } },
  { "$lookup": {
    "from": Sender.collection.name,
    "let": { "senderId": "$senderId" },
    "pipeline": [
       { "$match": { "$expr": { "$eq": [ "$_id", "$$senderId" ] } } }
     ],
     "as": "sender"
  }},
  { "$lookup": {
    "from": Receiver.collection.name,
    "let": { "receiverId": "$receiverId" },
    "pipeline": [
       { "$match": { "$expr": { "$eq": [ "$_id", "$$receiverId" ] } } }
     ],
     "as": "receiver"
  }}
 ])

如果您在 3.6 之前 mongodb版

db.collection.aggregate([
  { "$match": { "$or": myArray } },
  { "$lookup": {
    "from": Sender.collection.name,
    "localField": "senderId",
    "foreignField": "_id",
    "as": "sender"
  }},
  { "$lookup": {
    "from": Receiver.collection.name,
    "localField": "receiverId",
    "foreignField": "_id",
    "as": "receiver"
  }}
 ])