Mongodb $in against a field of objects of array instead of objects of array

前端 未结 3 1950
北恋
北恋 2021-02-19 13:22
arr=[{field1:,field2:

I want to use the $in operator against the field1 of arr. I

3条回答
  •  闹比i
    闹比i (楼主)
    2021-02-19 13:44

    You need to extract the "location" fields from your input array and feed them to $in:

    var locs = arr.map(function(x) { return x.location } );
    db.collection.find({ "fieldx": { "$in": locs } })
    

    For reference here I'm going to re-write your question for you:

    I have a collection that contains documents like this:

    { "fieldx": "NY" }
    { "fieldx": "LA" }
    { "fieldx": "SF" }
    

    What I have is an input array that is defined like this:

    var arr = [
        { "name": "foo", "location": "NY"},
        { "name": "bar", "location": "LA"},
        { "name": "foobar", "location": "NZ"}
    ];
    

    Now I want to write a query to find all the documents that match the "location" field in the array I have for input.

    How do I do I do that?

    I have tried:

    db.collection.find({ "fieldx": { "$in": arr } })
    

    But that does not match.

提交回复
热议问题