【问题标题】:How to search by a specific object value in array and return only the object searched in mongoDB如何通过数组中的特定对象值进行搜索并仅返回在 mongoDB 中搜索到的对象
【发布时间】:2019-07-22 14:04:07
【问题描述】:

我正在尝试查询嵌套在数组中的对象值并仅返回该值(连同它嵌套的整个对象)

我尝试了以下代码,但它返回了附属数组中的所有附属,而我只想要我搜索的那个:

// data structure : 
{
  _id: 1,
  name: vendorName,
  countryCode: US,
  affiliates: [{
      number: 1,
      name: affName
    },
    {
      number: 2,
      name: affName
    }
  ]

async function getDetails(user){

    let vendorQuery = {
        countryCode: user.countryCode,
        affiliates: {
          $elemMatch: {
            number: user.affiliateNumber
          }
        }
    }
    let db = await mongoService.connect()
    const collection = db.collection('vendors');
    let vendorDetails = await collection.find( vendorQuery, {'affiliates.$':1} ).toArray()
    console.log('brokerDetails : ',brokerDetails);

    return vendorDetails
}

因此,在上面的代码中,我希望返回供应商对象,但仅限于匹配的附属公司,而不是全部

【问题讨论】:

  • 您需要按照this answer 使用.project() 方法语法。喜欢 - let vendorDetails = await collection.find( vendorQuery).project({'affiliates.$':1}).toArray()
  • 谢谢,成功了!我不明白为什么 Docs id 中的语法不同。还是谢谢

标签: javascript node.js mongodb vue.js


【解决方案1】:

您需要使用 $ 投影运算符仅从数组中返回匹配的值。

另外,affiliatesQuery 需要 stop 成为 countryQuery 的一部分,并且整个应该是 find 查询的第一个参数。

find 查询的第二个参数应该是 projection

试试这个:

let countryQuery = {
    countryCode: user.countryCode,
    affiliates.number: user.affiliateNumber
  }

  let db = await mongoService.connect()
  const collection = db.collection('vendors');
  let vendorDetails = await collection.find(countryQuery, {'affiliates.$':1}).toArray()

【讨论】:

  • 感谢您的回答,但我仍然得到附属数组中的 2 对象
  • 你能显示你的查询吗,你尝试了什么,因为 $ 只返回一个元素(数组中的第一个匹配元素)
  • 是的,我已经按照新的修改了代码,请看一下
  • 显然应该是 collection.find(vendorQuery).project({'affiliates.$':1}).toArray() ,感谢您的帮助
  • 也一样,我建议的也是投影语法,不知道为什么不适合你。
【解决方案2】:

你可以使用聚合管道

const db = await mongoService.connect();
const collection = db.collection('vendors');
const result = await collection.aggregate([
  // query documents
  {
    $match: {
      countryCode: user.countryCode,
      'affiliates.number': user.affiliateNumber,
    }
  },
  // unwind affiliates array
  {
    $unwind : '$affiliates',
  },
  // filter docs again
  {
    $match: {
      'affiliates.number': user.affiliateNumber,
    },
  },
  // you can even replace root of the doc and return just object you need
  {
    $replaceRoot: { newRoot: "$affiliates" }
  }
])

return result

【讨论】:

    猜你喜欢
    • 2021-05-26
    • 2015-07-06
    • 2021-11-12
    • 1970-01-01
    • 2017-07-22
    • 2014-10-22
    • 2012-12-12
    • 1970-01-01
    相关资源
    最近更新 更多