search

Home  >  Q&A  >  body text

mongoose - 用mongodb 查询,用数组的每个元素来匹配字符串的值

有个document 查询全部结果如下:

db.order.find();

{ "_id" : ObjectId("58464c481dd68f2bcc8c280b"), "teamId" : "580493941a81901a6cabe9b1"},
{ "_id" : ObjectId("5848d4deffe1c81858b7648f"), "teamId" : "580493941a81901a6cabe9b1"},
{ "_id" : ObjectId("5848d557ee026d288000c922"), "teamId" : "581c33eb4d901f06f8ca4c65"}

现在有个需求,是查询出 teamId 与 数组中元素匹配的数据。比如,条件数组如下:

const array = ['580493941a81901a6cabe9b1'];

请问查询语句应该怎样写,可以查询出一下两条数据:

{ "_id" : ObjectId("58464c481dd68f2bcc8c280b"), "teamId" : "580493941a81901a6cabe9b1"},
{ "_id" : ObjectId("5848d4deffe1c81858b7648f"), "teamId" : "580493941a81901a6cabe9b1"},

请赐教,谢谢。

巴扎黑巴扎黑2757 days ago918

reply all(2)I'll reply

  • 天蓬老师

    天蓬老师2017-05-02 09:25:36

    Um, I still blame myself for being lazy.
    I checked the documents just now and I immediately knew how to check/embarrassed

    Post the query statement directly:

    db.order.find({teamId: {$in: ['580493941a81901a6cabe9b1']}});

    If you encounter a problem, check the documentation first.

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-05-02 09:25:36

    When I first saw this problem, I thought it should be handled using the $in operator. I thought it was a relatively simple problem.

    Looking at your question carefully, the data in the array is the string of _id. I am wondering if there is an input error and whether it is necessary to compare the values ​​of _id and array.

    Before comparison, the strings in the array need to be converted to ObjectId.

    for (i in arraySrc) {arrayTgt.push(ObjectId(ArraySrc[i]));}

    Then

    db.order.find({_id : { $in : arrayTgt}})

    For reference.

    reply
    0
  • Cancelreply